Fireworks 2

Same particle system, different use

by schrodingers

CSS

body {
  background-color: #000000;
  margin: 0;
  overflow: hidden;
}

JavaScript

var SCREEN_WIDTH = window.innerWidth,
  SCREEN_HEIGHT = window.innerHeight,
  mousePos = {
    x: 400,
    y: 300
  },

  // create canvas
  canvas = document.createElement('canvas'),
  context = canvas.getContext('2d'),
  particles = [],
  MAX_PARTICLES = 300,
  colorCode = 0;

// init
$(document).ready(function() {
  document.body.appendChild(canvas);
  canvas.width = SCREEN_WIDTH;
  canvas.height = SCREEN_HEIGHT;
  setInterval(changeColor, 2000);
  setInterval(loop, 1000 / 30);
});

$(document).mousemove(function(e) {
  e.preventDefault();
  mousePos = {
    x: e.clientX,
    y: e.clientY
  };
});

function loop() {
  // update screen size
  if (SCREEN_WIDTH != window.innerWidth) {
    canvas.width = SCREEN_WIDTH = window.innerWidth;
  }
  if (SCREEN_HEIGHT != window.innerHeight) {
    canvas.height = SCREEN_HEIGHT = window.innerHeight;
  }

  // clear canvas
  context.fillStyle = "rgba(0, 0, 0, 0.1)";
  context.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);

  makeParticle(5);

  var existingParticles = [];

  for (var i = 0; i < particles.length; i++) {
    particles[i].update();

    // render and save particles that can be rendered
    if (particles[i].exists()) {
      particles[i].render(context);
      existingParticles.push(particles[i]);
    }
  }

  // update array with existing particles - old particles should be garbage collected
  particles = existingParticles;

  while (particles.length > MAX_PARTICLES) {
    particles.shift();
  }
}

function changeColor() {
  colorCode = Math.floor(Math.random() * 360 / 10) * 10;
}

function makeParticle(count) {
  for (var i = 0; i < count; i++) {
    var particle = new Particle(mousePos);
    var angle = Math.random() * Math.PI * 2;
    var speed = Math.random() * 10 + 2;

    particle.vel.x = Math.cos(angle) * speed;
    particle.vel.y = Math.sin(angle) * speed;

    particle.size = 10;

    // particle.fade = 0.02;
    particle.gravity = 0.2;
    particle.resistance = 0.92;
    particle.shrink = 0.92;

   ...