javascript - 尝试使用 Canvas 工作来获取 setTimeout

标签 javascript animation canvas settimeout

刚开始使用 canvas 和 javascript,无法理解为什么此代码段中的 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();
});

最佳答案

你的 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();

关于javascript - 尝试使用 Canvas 工作来获取 setTimeout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12650819/

相关文章:

javascript - 使用 npm 安装最新版本的包

javascript - react native : iOS dictation unable to clear text input

html - CSS 动画无法识别嵌套跨度

javascript - Javascript 中点缀字体的坐标

javascript - 复制 Canvas 时禁用除 1 个 Canvas 之外的所有 Canvas 上的对象?

javascript - 具有数据库关系的 Django 的 ModelForm 中的 MultichoiceField

javascript - 使用 snap.svg 沿 svg 路径对对象进行动画制作和定向

Android解锁像滑动手势

javascript - 当按下左键或右键时仅在 Canvas 中旋转特定图像

javascript - 如何在AngularJS中获取offsetHeight、scrollHeight