Tuesday 4 December 2012

Bouncing a ball on HTML5 Canvas

Canvas provides a nice interface to draw anything on it. Canvas doesn’t support animations by default, but as we write JavaScript to do anything on canvas, we can create animations too. Let’s see how we can create a basic animation to bounce a ball inside boundaries of canvas.

Let’s create a ball on the canvas. We can do it by drawing a circle and filling some color inside it. Following code shows how to do it:
function draw(){
    context.beginPath();
    context.fillStyle="green";
    context.arc(10,10,20,0,Math.PI*2,true);
    context.closePath();
    context.fill();
}
Since we have to move the ball on canvas, we may say that we have to draw the ball over and over at different positions. Before drawing the ball at next position, we must clear the ball already drawn. And this logic has to be repeated after certain time.

Let’s modify the draw function defined above to draw the ball at different positions. The logic involves:
  • Clearing the canvas
  • Drawing the ball at a position
  • Calculating next position to draw the ball

Below code implements this logic:
function draw()
{
    context.clearRect(0,0,300,300);
    context.beginPath();
    context.fillStyle="green";
    context.arc(x,y,20,0,Math.PI*2,true);
    context.closePath();
    context.fill();  
    
    if(x+xShift > width || x+xShift < 0)
        xShift=0-xShift;
    if(y+yShift > height || y+yShift < 0)
        yShift=0-yShift;
    
    x+=xShift;
    y+=yShift;
}
On page load, we can use setInterval function to call draw function after certain interval.
setInterval(draw,20);



Happy coding!

1 comment:

Note: only a member of this blog may post a comment.