Html5画布动画不能正常工作

Gau*_*kur 5 javascript jquery html5 canvas

我想在画布上创建一个动画.它第一次工作正常,但是当通过setTimeout添加新元素时,所有元素的速度都会提高.谁能告诉我为什么这个速度在增加.小提琴链接

  var canvas = $("#canvas")[0],
    context = canvas.getContext("2d"),
    bloons = {},
    bloonIndex = 0;

var c_wdh = 360,
    c_hgt =  540;


function createBloon(x, y) {
  this.x = x;
  this.y = y; 
  this.vx = 1,
  this.vy = 3;
  bloonIndex++;
  bloons[bloonIndex] = this;
  this.id = bloonIndex;
}

createBloon.prototype.drawImage = function() {
   this.y -= this.vy;
   context.fillStyle = "#FF0000";
   context.fillRect(this.x, this.y, 50, 50);
   if(this.y <= -120){
      delete bloons[this.id];  
   }
};


var nob = 0;
var i = 1;
var rendorBloon = setInterval(function(){ 
    bloons[i] = new createBloon(Math.random() * c_wdh, c_hgt);
    var animate = setInterval(function () {
      context.clearRect(0, 0, c_wdh, c_hgt);          
      for (var i in bloons){
         bloons[i].drawImage();
      }
    }, 30); 

    i++; 
    nob++;
    if(nob >= 10){
      clearInterval(rendorBloon);
    }    
}, 1000);
Run Code Online (Sandbox Code Playgroud)

ElC*_*Net 0

我将尝试向您解释为什么动画会加速。每次调用都会创建rendorBloon setInterval一个新的。setInterval接下来的步骤解释了该过程:

1 - 第一次运行rendorBloon setInterval(1 秒):

    1 setInterval is created. 1 setInterval is running, it will run every 30 milliseconds
Run Code Online (Sandbox Code Playgroud)

2 - 第二次运行rendorBloon setInterval(2 秒):

    1 setInterval is created. 2 setInterval are running, they will run every 30 milliseconds
Run Code Online (Sandbox Code Playgroud)

3 - 第三轮rendorBloon setInterval(3秒):

    1 setInterval is created. 3 setInterval are running, they will run every 30 milliseconds
Run Code Online (Sandbox Code Playgroud)

4 - ... 继续 10 次

在每次rendorBloon执行中,setInterval都会创建一个新的,并且每次setInterval都会执行drawImage将图像向上移动 3 个像素的方法。当您清除rendorBloonsetInterval 时,您将有 10 个函数尝试移动每个框。结果:第一次迭代时盒子移动 3 个像素,第二次迭代移动 6 个像素,第三次迭代移动 9 个像素,然后继续。

我创建了一个新的jsfiddle改变了一些事情:

1 - 将两者分开setIntervals

2 - 将动画逻辑移至动画函数。

3 - 将删除框移至动画功能。

4 -drawImage直接在createBloon函数中创建方法,避免prototype.

animate setInterval5 -动画完成后清除。

6 - 确保所有框都使用c_wdh - width of the boxes随机值绘制在画布内。

这里有新的jsfiddle