Summary -

In this topic, we described about the Canvas Animation with detailed example.

setInterval() and setTimeout() methods used to produce an animation. HTML5 canvas offers essential methods to draw a picture and remove it totally. We can take Javascript support to mimic great animation over an HTML5 canvas.

Following are the two crucial Javascript procedures which would be utilized to animate a picture on a canvas –

Method Description
setInterval(callback, time); This process continually executes the provided code later a given time (milliseconds).
setTimeout(callback, time); This process executes the provided code only once later a given time (milliseconds).

Example -

Following example shows how to turn a small picture continuously animating -

   <script type = "text/javascript">
      var pattern = new Image();
      function myanimate() {
			pattern.src = img/2leftarrow.png';
			setInterval(animateShape, 75);
      function animateShape() { 
		// get the canvas element using the DOM
		var canvas = document.getElementById('mycanvas'); 
		// use getContext to use the canvas for drawing
		var ctx = canvas.getContext('2d'); 
		ctx.fillStyle = 'rgba(0,0,0,0.4)';
		ctx.strokeStyle = 'rgba(0,90,90,0.4)';;
		var time = new Date();
		ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + (
			(2*Math.PI)/6000)*time.getMilliseconds() );
 <body onload = "myanimate();">
	<canvas id = "mycanvas" width = "500" height = "350" 
		style="border:2px solid #00d3d3;" ></canvas>


Browser Support

The following browsers with versions in the table indicates the initial browser version that completely endorses the above methods.

Property Chrome Edge Firefox Safari Opera
Yes 9.0 and above Yes Yes Yes