Particle Test
by soulwire
HTML
<canvas id="canvas" width="500" height="500"></canvas>
CSS
html, body {
background-color: #111;
padding: 0;
margin: 0;
}
JavaScript
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// Gravitational constant
var G = 9.81;
var NUM_PARTICLES = 100;
var particles = [];
var mouseX = 0;
var mouseY = 0;
var mp = new Particle(250,250,1.0);
function Particle(x,y,mass) {
this.x = x;
this.y = y;
this.fx = 0;
this.fy = 0;
this.vx = 0;
this.vy = 0;
this.mass = mass;
};
Particle.prototype.draw = function(ctx) {
ctx.beginPath();
ctx.arc(this.x, this.y, 2 + this.mass * 10, 0, Math.PI * 2);
ctx.closePath();
ctx.fillStyle = 'rgba(255,255,255,0.5)';
ctx.fill();
};
function init() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
for(var i = 0; i < NUM_PARTICLES; i++) {
particles[i] = new Particle(Math.random()*500,Math.random()*500,Math.random());
}
update();
};
function update() {
canvas.width = canvas.width;
ctx.globalCompositeOperation = 'lighter';
mp.draw(ctx);
mp.x = mouseX;
mp.y = mouseY;
var p, f, dx, dy, dSq;
for(var i = 0; i < NUM_PARTICLES; i++) {
p = particles[i];
dx = mp.x - p.x;
dy = mp.y - p.y;
dSq = dx*dx + dy*dy;
if(dSq > 0.0001) {
// Compute force
f = (G * mp.mass * p.mass) / dSq;
p.fx = dx * f;
p.fy = dy * f;
p.fx /= p.mass;
p.fy /= p.mass;
// Integrate
p.vx += p.fx;
p.vy += p.fy;
p.x += p.vx;
p.y += p.vy;
p.vx *= 0.99;
p.vy *= 0.99;
p.fx = 0;
p.fy = 0;
p.draw(ctx);
}
}
setTimeout(update, 1000 / 30);
};
canvas.addEventListener('mousemove', function(e){
mouseX = e.offsetX;
mouseY = e.offsetY;
}, false);
init();