a blog for those who code

Friday 30 October 2015

Bouncing Ball Game using HTML5 Canvas Element - Part 1

In this post we will be discussing about bouncing ball game using HTML5 Canvas Element and requestAnimationFrame. In our previous post we have discussed about Bouncing Balls Animation using HTML5 Canvas Element, we are going to continue our study and create a game in HTML5. As you might know requestAnimationFrame 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.

Let Start Some Coding : In our previous post, we have created a Ball Class, we will be using the same class here as well. In addition to that we have a Paddle class as shown below.

function Paddle() {
  this.paddleWidth = 100;
  this.draw = function(x) {
    context.save();
    context.fillRect(paddleXValue, 385, this.paddleWidth, 15);
    context.restore();
  }
  this.paddleMove = function() {
    if(right) { 
      paddleXValue += 10 
      if(paddleXValue + this.paddleWidth > canvas.width) 
        paddleXValue = canvas.width - this.paddleWidth 
      }
    }
    else if(left) { 
      paddleXValue -= 10 
      if(paddleXValue < 0) { paddleXValue = 0 }
    }
  }
}

This class will create a paddle at the bottom of the canvas and on the click of left or right arrow, it will move accordingly. We have also added a mouse event listener as shown below, which will detect if right or left arrow is been clicked or not.

function onKeyDown(e) {
  if(e.keyCode === 39 ) right = true;
  if(e.keyCode === 37) left = true;
}

function onKeyUp(e) {
  if(e.keyCode === 39 ) right = false;
  if(e.keyCode === 37) left = false;
}

document.addEventListener("keydown", onKeyDown, false);
document.addEventListener("keyup", onKeyUp, false);

And last but not the least we will create our animateFunction which will do the drawing on the canvas by calling the requestAnimationFrame as shown below :

function animateFunction() {
  context.clearRect(0, 0, canvas.width, canvas.height);
  ball.draw();
  paddle.paddleMove();
  paddle.draw(paddleXValue);
  if(running) {
    requestAnimationFrame(animateFunction);
  }
}

We also checking that if the ball touched the ground and not the paddle, we are stopping the animation.

Full Source Code

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

No comments:

Post a Comment