Particles
palline colorate
by velthune
HTML
<canvas id="myCanvas" width="640" height="640" style="border: 5px solid black;"
onclick="generate()" ></canvas>
JavaScript
/* Function called first */
$(document).ready(function() {
Math.nRandom = function(){
return Math.random() * 2 - 1;
};
console.log("Init");
var canvas;
canvas = $("#myCanvas");
//canvas.css({height: '400', width:'400', border: '10px solid black'});
console.log("end init");
});
var Particle = function(a,b){
this.x = Math.random() * $("#myCanvas").width();
this.orX = this.x;
this.y = Math.random() * $("#myCanvas").height();
this.orY = this.y;
this.r = Math.random() * 20 + 5;
this.vx = Math.nRandom() * 30;
this.vy = Math.nRandom() * 30;
this.dt = 0.05;
var color = 'hsla(' + Math.floor(Math.random() * 360) + ',100%, 50%, 1)';
this.draw = function(){
console.log("Function draw()");
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
};
this.update = function(){
this.x += this.vx * this.dt;
this.y += this.vy * this.dt;
console.log("X: " + this.x + " Y: " + this.y);
if(this.x > $("#myCanvas").width() + this.r ||
this.x < 0 - this.r ||
this.y > $("#myCanvas").height() + this.r ||
this.y < 0 - this.r) {
this.x = this.orX;
this.y = this.orY;
}
};
};
var ctx = document.getElementById('myCanvas').getContext('2d');
var ptclArr = [];
function addPtcls(nmbr){
for(var i = 0; i < nmbr; i++){
var p = new Particle();
ptclArr.push(p);
};
};
addPtcls(44);
setInterval(function(){
ctx.clearRect(0, 0, $("#myCanvas").width(), $("#myCanvas").height());
for(var i = 0; i < ptclArr.length; i++) {
ptclArr[i].update();
}
for(var i = 0; i < ptclArr.length; i++) {
ptclArr[i].draw();
}
});
function generate(nmbr){
console.log("miao");
addPtcls(1);
};