【发布时间】:2012-04-16 20:05:41
【问题描述】:
我正在使用 Javascript 为 HTML5 Canvas 动画编写代码。我为此使用requestAnimFrame。动画效果很好。但是当我在使用requestAnimFrame 或setTimeout 的函数中添加循环(for 或while)时,动画不起作用。添加循环对我来说很重要。有什么建议可以让这成为可能吗?
function animate(lastTime) {
var date = new Date();
var time = date.getTime();
var timeDiff = time - lastTime;
var linearSpeed = 100;
var linearDistEachFrame = linearSpeed * timeDiff / 1000;
var currentX = LINE.x;
var currentY = LINE.y;
var newY = currentY + linearDistEachFrame;
var newX = currentX + linearDistEachFrame;
context.beginPath();
context.moveTo(LINE.x, LINE.y);
lastTime = time;
var Xindex=LINE.arrayX.indexOf(newX);
//here am getting error..if i replace this with 'if' its working fine..and even if there is not a single LOC it doesnt work
while(Xindex!=-1) {
//processes the loop
}
context.lineTo(LINE.x, LINE.y);
context.fillStyle = "red";
context.fill();
context.lineWidth = LINE.borderWidth;
context.strokeStyle = "red";
context.stroke();
// request new frame
requestAnimFrame(function() {
animate(lastTime);
});
}
【问题讨论】:
-
代码在哪里?我们应该猜测问题出在哪里吗?
-
请提供一些代码...哪些有效,哪些无效...您的结构可能是原因
-
添加了代码..如果我将'while'替换为'if'它可以工作..即使循环内没有代码它也不起作用......
-
您是否可能处于无限循环中?如果您在错误条件下循环,并且循环中没有任何内容可以更改条件,那么它将永远不会继续......
-
实际上 'Xindex' 返回 -1 并且从一开始就不会进入循环...
标签: javascript html5-canvas html5-animation