刚开始使用 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/