【问题标题】:Trying to get setTimeout with canvas working试图通过画布工作获得 setTimeout
【发布时间】:2025-12-13 06:40:01
【问题描述】:

刚开始使用 canvas 和 javascript,我无法理解为什么这个 sn-p 中的 setTimeout 不起作用。我最初认为它会触发每一帧,因为它包含在循环中。我也尝试在 animate 函数中移动它,但无济于事。

$(document).ready(function(){
var canvas = $('#myCanvas');
var context = canvas.get(0).getContext('2d');   

var Shape = function(x1,y1,x2,y2){
    this.x1 = x1
    this.y1 = y1
    this.x2 = x2
    this.y2 = y2
}

var shapes = new Array();

shapes.push(new Shape(0,0,50,50));
shapes.push(new Shape(50,50,50,50));
shapes.push(new Shape(0,100,50,50));
shapes.push(new Shape(50,150,50,50));
shapes.push(new Shape(0,200,50,50));

function animate(){
    for (i=0;i<shapes.length;i++){
        context.clearRect(0,0,500,500);
        context.fillRect(shapes[i].x1,shapes[i].y1,shapes[i].x2,shapes[i].y2);
        setTimeout(animate, 500);
    };
};
animate();
});

【问题讨论】:

    标签: javascript animation canvas settimeout


    【解决方案1】:

    你的 animate() 有问题。

    • 不要在循环中执行setTimeout。这将冻结您的浏览器。
    • for 循环中的代码绘制矩形并立即擦除它。这就是您看不到动画的原因。

    考虑像这样更改您的代码。

      var i = 0;
      function animate(){
          context.clearRect(0,0,500,500);
          context.fillRect(shapes[i].x1,shapes[i].y1,shapes[i].x2,shapes[i].y2);
          i++;
          if (i == shapes.length) i = 0;
          setTimeout(animate, 500);
      };
      animate();
    

    【讨论】:

    • 谢谢!像魅力一样工作。我误读了 setTimeout 的工作原理。
    【解决方案2】:

    setTimeout 在循环中创建问题,因为您正在专心地覆盖 timeOutId。 你必须改变你的逻辑。将 setTimeout 置于循环之外。

    【讨论】: