HTML5 : animating in Canvas

It may seem exciting to read the title as to get some animation right away in HTML5 Canvas. But the thing is, there is no direct API for animation. So the point is animation is done through the timer API of javascript. There are two different APIs for timing.

function onTimeout() { 
alert("time is over");
}; 
var timeout = setTimeout(onTimeout, 3000);

The code above will call the “onTimeout” function after “3000″ milliseconds. But the thing is this is only called once.
Now we have another API, which give us the ability to call a function at a regular interval and its called as below

onTimer=function(){
  //code here will be called at a regular interval of 100 milliseconds
};
var timer=setInterval(onTimer,100);

Now, if you look at the source files and the resulting HTML file, there is an animation of a bar going animating from left to right. This is done with the code below.

onTimer=function(){
		context_one.beginPath();//creates a new drawing
		context_one.moveTo(xpos, ypos);
		context_one.lineTo(xpos+1, ypos);
		//define the pen
		context_one.strokeStyle = "#0F0";
		context_one.lineWidth   = 50;
		//make the lines visible
		context_one.stroke();
		xpos+=1;
		//
		if(xpos>=canvas_one.width)
		{
			clearInterval(timer);
			alert ("Animation complete.");
		}
	};

And then calling the function as

var timer=setInterval(onTimer,100);

The function will be called on every 100 milliseconds. We can smaller the interval to smoothen the animation.

Thats simple, is not it! Happy animating :)