EDIT: I misunderstood your original post. For your situation, you do not need to clear the previous animation only when the animation is complete to start it all.
jsfiddle: http://jsfiddle.net/Grimbode/TCmrg/
Here are two websites that have helped me understand how animations work.
http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/
In this article, William talks about sprite animation, which, of course, is not what interests you. Interestingly, it uses the recursive loop function created by Paul Irish.
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
This function will try to rotate 60 times per second (essentially at 60 frames per second).
(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); }; }());
So the big question is: how does it work? You just need to do this:
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(){ context.clearRect(old_position.x, old_position.y, width, height) new_position = {x: 100, y: 200}; old_position = new_position; }
After this step, you will probably like your question. "Well, I have some kind of animation, but I donβt want my line animation to rotate at 60 frames per second." If you read the williams message, it uses tics.
The websites I am connected with are much better at explaining than I could. I suggest you read them. [= I had fun reading them.
And: Here is your jfiddle :)
http://jsfiddle.net/Grimbode/TCmrg/