a blog for those who code

Wednesday, 28 October 2015

Bouncing Balls Animation using HTML5 Canvas Element

In this post we will be discussing about creating bouncing ball animation using HTML5 canvas element. Like Basic Animation using HTML5 Canvas Element, here also we will use requestAnimationFrame. which will tell the browser that you wish to perform the animation and it also requests to update an animation before the next repaint by the browser.

For bouncing balls animation at first we need to create a Ball class as shown below :

function Ball(x, y, dx, dy, radius, color) {

  if(x === undefined) { x = 50 }
  if(y === undefined) { y = 50 }
  if(dx === undefined) { dx = 2 }
  if(dy === undefined) { dy = 3 }
  if(radius === undefined) { radius = 10 }
  if(color === undefined) { color = 'green' }
  this.radius = radius; this.color = color; 
  this.x = x; this.y = y; 
  this.dx = dx; this.dy = dy;
  this.draw = function() {
    context.save();
    context.beginPath();
    context.arc(this.x, this.y, this.radius, 0, 2*Math.PI);
    context.closePath();

    this.y += this.dy; this.x += this.dx;
    if(this.y >= canvas.height - this.radius) 
    { 
      this.y = canvas.height - this.radius; this.dy = -this.dy; 
    }
    else if(this.y < 0 + this.radius) 
    { 
      this.y = 0 + this.radius; this.dy = -this.dy; 
    }
    
    if(this.x >= canvas.width - this.radius) 
    { 
      this.x = canvas.width - this.radius; this.dx = -this.dx; 
    }
    else if(this.x < 0 + this.radius) 
    { 
      this.x = 0 + this.radius; this.dx = -this.dx; 
    }
    context.fillStyle = this.color; 
    context.fill(); 
    context.restore();
  }
}

In the above code we have written a draw function which will create the ball according to the radius and color provided. Note we are saving the context at the first line and then restoring it at last line of the draw function, because we do not want our context to get updated with the color supplied. Context saved will be stacked, the last one that has been saved will be restored by the next call to restore(). So it is very important to have one restore with every save.

Now we have to create a new instance of the ball class to start the animation as shown below :

ball = new Ball(x, y, dx, dy, radius, color);

Full Source Code

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

No comments:

Post a Comment

Contact Us

Name

Email *

Message *

Sponsers

Best Hosting Plans

CC License