Bouncing Ball Game using HTML5 Canvas Element - Part 1

来源:转载

Let Start Some Coding :In ourprevious 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.



分享给朋友:
您可能感兴趣的文章:
随机阅读: