title: How to make canvas particles follow mouse with JS?
body: <p>I want to make the particles follow the mouse and I am not sure on how to do that. </p>
  
  <p>I figured I can replace the x and y with the mouses position but I can figure that out either.</p>
  
  <p>I would appreciate an almost exact answer and not examples please.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = function() {
    var canvas = document.createElement("canvas"),
      c = canvas.getContext("2d"),
      particles = {}
    particleIndex = 0,
      particleNum = Math.random() * 2;
  
  
    canvas.width = 400;
    canvas.height = 400;
  
    document.body.appendChild(canvas);
  
    c.fillStyle = "black";
    c.fillRect(0, 0, canvas.width, canvas.height);
  
    function Particle() {
      this.x = canvas.width / 10;
      this.y = canvas.height / 2;
  
      this.vx = Math.random() * 10 - 5;
      this.vy = Math.random() * 10 - 5;
  
      this.gravity = .2;
  
      particleIndex++;
      particles[particleIndex] = this;
  
      this.id = particleIndex;
  
      this.life = 0;
      this.maxLife = Math.random() * 30 + 10;
  
      this.color = "rgb(" + parseInt(Math.random() * 255, 10) + ",0,0)";
      this.color2 = "hsl(" + parseInt(Math.random() * 255, 10) + ",50%,50%)";
    }
  
    Particle.prototype.draw = function() {
      this.x += this.vx;
      this.y += this.vy;
  
      if (Math.random() &lt; 0.1) {
        this.vx = Math.random() * 10 - 5;
        this.vy = Math.random() * 10 - 5;
      }
      this.vy += this.gravity;
      this.life++;
  
      if (this.Life &gt;= this.maxLife) {
        delete particles[this.id];
      }
  
      c.fillStyle = this.color2;
      c.fillRect(this.x, this.y, 10, 10);
  
    };
  
  
    //var p = new Particle();
  
    setInterval(function() {
      c.fillStyle = "rgba(0,0,0,0.5)";
      c.fillRect(0, 0, canvas.width, canvas.height);
      for (var i in particles) {
        particles[i].draw();
      }
      for (var i = 0; i &lt; particleNum; i++) {
        new Particle();
      }
    }, 30);
  
  };</code></pre>
  </div>
  </div>
  </p>