The canvas element is part of HTML5 and allows for dynamic, scriptable rendering of 2D shapes and bitmap images.
Canvas consists of a drawable region defined in HTML code with height and width attributes.
JavaScript code may access the area through a full set of drawing functions similar to those of other common 2D APIs, thus allowing for dynamically generated graphics.

In this example I’m going to show you how to animate a single bouncing ball on a web page using the canvas tag.

h5canvas_img
The html page is very simple, it will look like the following one:

<html>
<body onLoad="init();">
<canvas id="ballCanvas" width="300" height="300" >
</canvas>
</body>
<script src="js/bBall.js"> </script>
</html>

Let’s start coding
As you can see we will start our animation calling the init function when the html body has been loaded, the init function will retrieve the DOM node for the canvas, then it will get the drawing context using getContext() method.

var theCanvas;
var theContext;
init()
{
theCanvas = document.getElementById('theCanvas');
theContext = theCanvas.getContext('2d');
}

 

Let’s start drawing the ball:
we will need at least the following info for the ball:
– the position, expressed in x and y
– the starting position for the ball (initially sets to the center of the canvas 150,150)
– the direction, expressed in deltax and deltay
– the direction for the ball sets to 5,-10

var x=150;
var y=150;
var deltax=5;
var deltay=-10;

and now the draw function:

function draw()
{

first of all we will clear the context, so each time we’ll draw the ball on a white canvas.
context.clearRect(0,0, 300,300);
then we'll draw the ball using the arc method
theContext.fillStyle="#0000ff";
theContext.arc(x,y,20,0,Math.PI*2,true);
theContext.closePath();
theContext.fill();
last we have to compute next position (if the new position go out of the canvas area we will change the direction)
if( x<0 || x>300)
dx=-dx;
if( y<0 || y>300)
dy=-dy;
x+=dx;
y+=dy;
}

Finally we have to call the draw function, we’ll call the function every 20 milliseconds from the init function using the setInterval(function)
init()
{
theCanvas = document.getElementById('theCanvas');
theContext = theCanvas.getContext('2d');
setInterval(draw,20);
}

The full source code:
The directory for our sample is the following:
.
|____index.html
|____js
| |____bBall.js

 

The source code for the index.html

 

The source code for bBall.js:

 

 

Gg1