刚开始使用canvas和javascript,无法理解为什么此代码段中的setTimeout无法正常工作。我最初以为它将触发每个帧,因为它包含在循环中。我已经尝试过在动画功能内移动它,但无济于事。
$(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();