a blog for those who code

Tuesday 27 October 2015

Basic Animation using HTML5 Canvas Element

In this post we will be discussing about creating basic animation using HTML5 canvas element. According to Wiki, animation is a process of creating the illusion of motion and shape change by means of the rapid display of a sequence of static images that minimally differ from each other.

In HTML5 we do the animation using requestAnimationFrame method, which tells the browser that you wish to perform the animation and it also requests to update an animation before the next repaint. requestAnimationFrame is supported in most of the browser as shown below.

PC : http://caniuse.com/#search=requestAnimationFrame

requestAnimationFrame runs a callback after the browser paints the screen unlike setTimeout which runs after specified time delay. Animations can be performed by at first clearing the context, then drawing the shape, then moving the shape and then start all over again.

Simple Animation Example using requestAnimationFrame

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var x = 0, y = 0, value = 2;


function animateFunction() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  context.fillRect(x, y, 50, 50);

  if( x >= 0 ){
    x += value;
    if( x > 150 ) { y += value; x -= value; }

  if( y > 150 ) { x = 0; y = 0; }


In the above code we are calling the requestAnimationFrame() with a callback animateFunction. In animateFunction we are at first clearing the rectangle and then filling the rectangle with the updated value of x and y. requestAnimationFrame calls the function only once so for the continuous animation we need to call requestAnimationFrame again at the end of the logic to get the updated frame.

Script Demo

Please Like and Share the CodingDefined Blog, if you find it knowledgeable and helpful.

No comments:

Post a Comment