Particles - Canvas

Add particles on a canvas

by Virginie LE GUEN BERTHEAUME

HTML

<div id="particles-area"></div>

CSS

#particles-area {
  height: 1000px
}

#particles-area>canvas {
  width: 100%;
  height: 100%;
}

JavaScript

var mergeJSON = function() {
  var destination = {},
    sources = [].slice.call(arguments, 0);
  sources.forEach(function(source) {
    var prop;
    for (prop in source) {
      if (prop in destination && Array.isArray(destination[prop])) {
        destination[prop] = destination[prop].concat(source[prop]);
      } else if (prop in destination && typeof destination[prop] === "object") { // Merge Objects
        destination[prop] = mergeJSON(destination[prop], source[prop]);
      } else {
        destination[prop] = source[prop];
      }
    }
  });
  return destination;
};

function ParticleCanvas(nbParticles, opts) {
  this.hasInit = false;
  this.paused = false;
  if (typeof(nbParticles) == 'object') {
    opts = nbParticles;
    nbParticles = 200;
  }
  if (!opts) {
    opts = {};
  }
  if (typeof(opts) == 'string') {
    opts = {
      elSelector: opts
    };
  }
  this.opts = mergeJSON({
    elSelector: 'body',
    effectDistance: 40,
    cursorDistance: 40,
    particles: {
      base: {
        color: '#272727',
        size: 4
      },
      selected: {
        color: '#d9326f',
        size: 5
      }
    },
    lineWidth: 0.1,
    speed: 1,
    refresh: 60
  }, opts);
  this.playPause = function() {
    this.paused = !this.paused;
  };
  this.init = function() {
    if (!this.opts.elSelector) {
      this.opts.elSelector = 'body';
    }
    this.el = document.querySelector(this.opts.elSelector);
    this.canvas = document.createElement('canvas');
    this.canvas.width = this.el.clientWidth;
    this.canvas.height = this.el.clientHeight;
    this.el.append(this.canvas);
    this.ctx = this.canvas.getContext('2d');
    this.particles = [];
    this.cursorOn = {
      x: -100,
      y: -100
    };
    this.hasInit = true;
    var that = this;
    window.addEventListener('resize', function() {
      that.canvas.width = that.el.clientWidth;
      that.canvas.height = that.el.clientHeight;
    });
    this.canvas.addEventListener('mousemove', function(e)...