Monday, 31 January 2011

HTML5: Animation Example Step By Step

HTML5: Animation Example Step by Step

Define canvas tag inside HTML (preferrably inside body tag):
<canvas id="moving_img_id" width="600" height="600"></canvas>

Define moving image inside javascript:
 var moving_image = new Image();  
 moving_image.src = 'imageToDraw.jpg'; 

Call getContext on canvas to get the context for drawing:

    var 2d_content = canvas.getContext('2d');;   //Save Context
    2d_content.translate(350,350); //Move to this location 350,350 in this case.
    2d_content.rotate(angle);//Rotate at various angles
    2d_content.translate(0,1);//Move to a new position   
    2d_content.drawImage(moving_image, 5, 5);//Draw the image   
    2d_content.restore();// Restore context

For Animation effect call the setInterval function which will internally call drawMovingImages (same function which will execute the steps mentioned above) function every 100 milliseconds.
setInterval(drawMovingImages, 100);

Try this and have fun :)


  1. Animation is an awesome gift from HTML5....... ByeBye Flash:)

  2. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.
    youtube html5 player