ES6 particles

by schrodingers

CSS

body {
  margin: 0;
  overflow: hidden;
}

canvas {
  /* width: 100%;
  height: 100%; */
}

JavaScript

let c = document.createElement('canvas'),
  ctx = c.getContext('2d');
document.body.appendChild(c);
let w = c.width = window.innerWidth;
let h = c.height = window.innerHeight;

function random(min, max) {
  var num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}

class Particle {
  constructor() {
    this.x = random(0, w);
    this.y = random(0, h);
    this.vx = Math.random(0.75, 3);
    this.vy = Math.random(0.75, 3);
    this.size = random(5, 15);
    this.color = ~~(Math.random() * 360);
  }

  draw() {
    ctx.beginPath();
    ctx.fillStyle = `hsla(${this.color}, 50%, 50%, 1)`;
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2, );
    ctx.fill();
    ctx.closePath();
  }
  update() {
    if (this.x + this.size >= w || this.x - this.size <= 0) this.vx = -this.vx;
    if (this.y + this.size >= h || this.y - this.size <= 0) this.vy = -this.vy;

    this.x += this.vx;
    this.y += this.vy;
  }
}

let [particles, num] = [new Array(), 100];
for (let i = 0; i < num; i++) {
  particles.push(new Particle());
}

function loop() {
  ctx.fillStyle = "rgba(0,0,0,0.95)";
  ctx.fillRect(0, 0, w, h);

  for (let particle of particles) {
    particle.update();
    particle.draw();
  }
  requestAnimationFrame(loop);
}


function reset() {
  c.width = window.innerWidth;
  c.height = window.innerHeight;
}
window.addEventListener("resize", reset);
reset();

loop();