如何使用JS跟随鼠标制作画布粒子?

时间:2016-01-22 04:25:00

标签: javascript html canvas

我想让粒子跟随鼠标,我不知道如何做到这一点。

我想我可以用鼠标位置替换x和y,但我也可以解决这个问题。

我希望得到一个几乎准确的答案而不是例子。

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() < 0.1) {
      this.vx = Math.random() * 10 - 5;
      this.vy = Math.random() * 10 - 5;
    }
    this.vy += this.gravity;
    this.life++;

    if (this.Life >= 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 < particleNum; i++) {
      new Particle();
    }
  }, 30);

};

0 个答案:

没有答案