Canvas particles

by sungsoonz

HTML

<canvas width="500" height="400"></canvas>

CSS

canvas {
  background: black;
}

JavaScript 1.7

const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let mousePos = { x: 0, y: 0 };
let particles = [];
let hue = 0;

window.addEventListener('resize', function() {
	canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

canvas.addEventListener('mousemove', function(e) {
	mousePos.x = e.x;
  mousePos.y = e.y;
  for (let i = 0; i < Math.random()*10+10; i++) {
		particles.push(new Particle(mousePos.x, mousePos.y));
  }
});



class Particle {
	constructor(x, y) {
  	this.x = x;
    this.y = y;
    this.size = Math.random() * 6 + 1;
    this.speedX = Math.random() * 3 - 1.5;
    this.speedY = Math.random() * 3 - 1.5;
    this.color = 'hsl(' + hue + ',100%, 50%)';
  }
  update() {
  	this.x += this.speedX;
    this.y += this.speedY;
    if (this.size > 0.2) this.size -= 0.1;
  }
  draw() {
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
  }
}


function handleParticles() {
	for (let i = 0; i < particles.length; i++) {
	  	particles[i].update();
			particles[i].draw();
/*       if (particles[i].size <= 0.3){
        particles.splice(i, 1);
        i--;
      } */
  }
}

function animate() {
	//ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = 'rgba(0,0,0,0.1)';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  handleParticles();
  hue+=5;
  requestAnimationFrame(animate);
}


animate();

/* function init() {
  for (let i = 0; i < 60; i++) {
    particles.push(new Particle(Math.random() * canvas.width, Math.random() * canvas.height));
  }
}

init(); */