Skip to content

Instantly share code, notes, and snippets.

@jamesporter
Created July 3, 2018 21:43
Show Gist options
  • Save jamesporter/d42496aeb4be56fd422b36f413ebcac3 to your computer and use it in GitHub Desktop.
Save jamesporter/d42496aeb4be56fd422b36f413ebcac3 to your computer and use it in GitHub Desktop.
Trace moment of random particles
body {
background: black;
}
<canvas id="canvas" width="480" height="320"></canvas>
const d_canvas = document.getElementById('canvas');
const context = d_canvas.getContext('2d');
const dt = 0.1;
let particles = [];
for(let i = 0; i < 10; i++){
particles.push({ x: 10, y: 10, vx: 1, vy: 1 });
}
const updateParticles = () => {
particles.forEach((particle,i) => {
particles[i] = { x: particle.x + particle.vx * dt,
y: particle.y + particle.vy * dt, vx: particle.vx + Math.random() * 0.1, vy: particle.vy + Math.random() * 0.1
}
if(particles[i].x > 480) particles[i].vx *= -1;
if(particles[i].x < 0) particles[i].vx *= -1;
if(particles[i].y < 0) particles[i].vy *= -1;
if(particles[i].y > 320) particles[i].vy *= -1;
})
}
const render = () => {
particles.forEach((particle, i) => {
context.fillStyle = "rgba(" + (255 - 60 * (i%3)) + "," + (255 - 60 * (i/3)) + ",0,1)";
context.fillRect(particle.x, particle.y, 1, 1);
})
updateParticles();
requestAnimationFrame(render);
}
render();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment