编辑:我误解了您的原始帖子。对于您的情况,您不需要清除之前的动画,只有在动画完成后才能重新开始。
jsfiddle:http://jsfiddle.net/Grimbode/TCmrg/
这里有两个网站帮助我了解动画的工作原理。
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
在这篇文章中,William 讲的是精灵动画,这当然不是你感兴趣的。有趣的是他使用了 Paul Irish 创建的递归循环函数。
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
此函数将尝试每秒旋转 60 次(因此基本上以 60 fps)。
(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
所以最大的问题是,这是如何工作的?你几乎只需要这样做:
function gameLoop () {
window.requestAnimationFrame(gameLoop);
renderLine();
}
var counter = 0;
var old_position = {x: 0, y: 0};
var new_position = {x: 0, y: 0};
var width = 10;
var height = 10;
function renderLine(){
/* Here you clear the old line before you draw the new one */
context.clearRect(old_position.x, old_position.y, width, height)
/* you update your new position */
new_position = {x: 100, y: 200};
/* Here you call your normal moveTo and lineTo and stroke functions */
/* update old position with the nwe position */
old_position = new_position;
}
在这一步之后,您的问题可能会喜欢。 “好的,我正在制作某种动画,但我不希望我的线条动画以 60 fps 的速度旋转”。如果您阅读威廉姆斯的帖子,他会使用“ticks”。
我链接的网站在解释方面做得比我做得更好。我建议你阅读它们。 [= 我读起来很开心。
并且:这是你的 jfiddle :)
http://jsfiddle.net/Grimbode/TCmrg/