Random Particles in Canvas

Written by Josh Fabean

15. January 2016

I made some randomly generated particles in canvas, best part is it made it to the front page of CodePen!

See the Pen Randomly Generated Particles by Josh Fabean (@fabean) on CodePen.

The bulk of the work I had to do was pretty simple, just loop and randomly come up with some numbers and use those numbers to display things on the screen.

for (let i=0; i<amountOfParticles; i++) {
  particles[i] = {
    y: Math.floor(Math.random() * canvas.height),
    x: Math.floor(Math.random() * canvas.width),
    speedX: (Math.floor(Math.random() * maxSpeed + 1) * (Math.random() < 0.5 ? -1 : 1)), 
    speedY: (Math.floor(Math.random() * maxSpeed + 1) * (Math.random() < 0.5 ? -1 : 1)),
    color: randomColor(),
    radius: Math.floor(Math.random() * maxSize)
  };
}

Once I’ve done that, in my render function I basically loop over it again but this time fill in some circles with the information I have.

for (let i=0; i<amountOfParticles; i++) {
  if (particles[i].x >= c.width || particles[i].x <= 0) {
    particles[i].speedX = -(particles[i].speedX);
  }

  if (particles[i].y < 0 || particles[i].y > c.height) {
    particles[i].speedY = -particles[i].speedY;
  }

  particles[i].x += particles[i].speedX; 
  particles[i].y += particles[i].speedY;

  drawCircle(particles[i]);
}

let drawCircle = (circle) => {
  ctx.fillStyle = circle.color;
  ctx.beginPath();
  ctx.arc(circle.x, circle.y, circle.radius, 0, Math.PI*2, true);
  ctx.fill();
}

All in all a very simple task, that a month or so would have been super confusing to me. Now that I’ve made a couple different projects using canvas it’s not some weird mythical thing.

You should play with canvas and learn a lot!

:wq