Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Developing a Game in JavaScript, HTML5 and Canvas

In this article we will learn how to make our first game with HTML5 and JavaScript. This will include movement of ball and paddles. This game comprises of a user and a bot.

We can easily make browser games with JavaScript and they are pretty much interesting games. Let’s start creating our first game in JavaScript. We will create HTML file and embed JavaScript within this file.

Listing 1. Initializing the game

	<canvas id="gameCanvas" width="800" height="600"></canvas>
		var canvas;
		var canvasContext;
		var ballX = 50;
		var ballY = 50;
		var ballSpeedX = 10;
		var ballSpeedY = 4;
		var player1Score = 0;
		var player2Score = 0;
		const WINNING_SCORE = 3;
		var showingWinScreen = false;
		var paddle1Y = 250;
		var paddle2Y = 250;
		const PADDLE_THICKNESS = 10;
		const PADDLE_HEIGHT = 100;

We are creating a HTML Canvas which can be used to build a JavaScript game. We have set the width and height of the Canvas to be 800*600 which can easily fit every device. In the above code snippet we are creating and initialising many different variables which are required for the proper functioning of the game.

 ballX = 50 
 ballY = 50 
denotes the initial coordinates of the ball and then we have set the speed of the moving ball in X and Y direction respectively. The initial score for both player and computer bot is zero and the winning score is a constant which is set to 3. You can set whatever winning score you want. We have created two constant variables which denotes the height and thickness of the paddle. These are created as constants because there is no need of changing the values as the game progresses.

Now we will create different functions in JavaScript that will handle different events of the game. Let's start by creating our first event handling function.

Listing 2. Handling Mouse Events

function calculateMousePos(evt) {
	var rect = canvas.getBoundingClientRect();
	var root = document.documentElement;
	var mouseX = evt.clientX - rect.left - root.scrollLeft;
	var mouseY = evt.clientY - - root.scrollTop;
	return {

function handleMouseClick(evt) {
	if(showingWinScreen) {
		player1Score = 0;
		player2Score = 0;
		showingWinScreen = false;

In the above code we have created a function "calculateMousePos" to get the exact X and Y coordinates of the mouse on the screen so that we can easily control the collision of the ball and the paddle. Here the coordinates of the mouse denotes the coordinates of the center of the paddle on the screen. After that we are storing the X and Y values of the mouse by subtracting the extra part i.e we are only calculating the coordinates with respect to our game area not the whole window. Recall that we have created the game window to be 800*600, so the coordinates will be calculated according to the game window not the whole browser window. We are returning the object which contains the X and Y coordinates of the mouse.

We have also created another function "handleMouseClick" which make sures which screen to display. Our game has 2 screens i.e one for playing the game and another for displaying the winner of the game with total points. So if the variable "showingWinScreen" is set to true then it will display the winning player and the score will be reset to zero. If it is false then it will continue displaying our game screen and score will be added each time the ball is not hitting the paddle.

Listing 3. Getting the Canvas

window.onload = function() {
	canvas = document.getElementById('gameCanvas');
	canvasContext = canvas.getContext('2d');

	var framesPerSecond = 30;
	setInterval(function() {
		}, 1000/framesPerSecond);

	canvas.addEventListener('mousedown', handleMouseClick);

		function(evt) {
			var mousePos = calculateMousePos(evt);
			paddle1Y = mousePos.y - (PADDLE_HEIGHT/2);

window.onload denotes that whenever the browser window loads for the first time, call a particular function. This time we have created an anonymous function, they are those functions which do not have names. We are using document.getElementById to get the Canvas which we have created using HTML and then we are defining the context of the Canvas. We can have both '2d' and '3d' Canvas but this time we only want '2d' Canvas for the paddle ball game. We are then defining the interval in milliseconds after which the game window will automatically update so that it can ensure good functioning of the game. We are calling two different functions i.e "moveEverything" and "drawEverything" which we will create in later part of this article. the setInterval function will automatically call itself after a particular amount of time and the time is specified in the function.

We are handling two different mouse events i.e clicking of the mouse and the moving of the mouse pointer on the game screen. Inside this we are calling the function to get the coordinates that we have already created and then storing the coordinates of the user paddle in the variable so that the paddle can move according to the mouse movement. We have subtracted the half of paddle height so that we are always matching the center of the paddle.

Listing 4. Handling Computer Movement

function ballReset() {
	if(player1Score >= WINNING_SCORE ||
		player2Score >= WINNING_SCORE) {

		showingWinScreen = true;


	ballSpeedX = -ballSpeedX;
	ballX = canvas.width/2;
	ballY = canvas.height/2;

function computerMovement() {
	var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
	if(paddle2YCenter < ballY - 35) {
		paddle2Y = paddle2Y + 6;
	} else if(paddle2YCenter > ballY + 35) {
		paddle2Y = paddle2Y - 6;

The first function here is ballReset which will reset the ball and place it at the center of the game window if any player wins. If the score of the player or the score of the computer bot is greater than the winning score then the variable showWinScreen will be set to true and it will display a different screen showing the winning player. After that we are setting the coordinates of the ball so that the ball it at the center of the game window whenever we are displaying the winning screen and also the score on both sides should be equal to zero.

Now let's handle the bot's paddle movement. We have created two different conditions i.e one when the ball is moving upwards and another when the ball is moving downwards. Everytime the ball is moving we are moving the computer bot by 6 pixels up and down which depends on the position of the ball. You can change the movements pixels and store a higher number if you want a difficult bot player.

Listing 5. Move Everything

function moveEverything() {
	if(showingWinScreen) {


	ballX = ballX + ballSpeedX;
	ballY = ballY + ballSpeedY;
	if(ballX < 0) {
		if(ballY > paddle1Y &&
			ballY < paddle1Y+PADDLE_HEIGHT) {
			ballSpeedX = -ballSpeedX;

			var deltaY = ballY
			ballSpeedY = deltaY * 0.35;
		} else {
			player2Score++; // must be BEFORE ballReset()
	if(ballX > canvas.width) {
		if(ballY > paddle2Y &&
			ballY < paddle2Y+PADDLE_HEIGHT) {
			ballSpeedX = -ballSpeedX;

			var deltaY = ballY
			ballSpeedY = deltaY * 0.35;
		} else {
			player1Score++; // must be BEFORE ballReset()
	if(ballY < 0) {
		ballSpeedY = -ballSpeedY;
	if(ballY > canvas.height) {
		ballSpeedY = -ballSpeedY;

Now let's create a function "moveEverything" which will handle the movement of the ball and the speed of the ball inside the game window.

After every instance we are setting the X and Y coordinates of the ball by adding the speed of the ball, this will ensure that the ball is kept moving at every point of time. Now if we four different condition i.e "ball is moving away from left of the canvas" , "ball is moving away from right of the canvas" , "ball is moving away from top of the canvas" and "ball is moving away from bottom of the canvas". Let's handle all these conditions one by one.

If the ball is moving away from the left of the Canvas then we will just reverse the speed of the ball in opposite direction so that the ball keeps moving but in different direction. If we look into the top and bottom position then if the ball is below the half of the height of Canvas then we are making sure that the ball bounces off the bottom of the Canvas and if the position of the ball is above the half of the Canvas then we are making the ball to bounce off the top of the Canvas. For the ball moving away from right of the Canvas we will simply reverse the direction of the ball so that the ball moves continuously. In this function we also have make sure that if the ball hits the paddle i.e bottom or top of the paddle than ball will move into different directions. If the ball is hitting the bottom of the paddle then the ball will bounce from the bottom of the game area and similar is the condition when ball is hitting the top of the paddle. These rules are for both user and the computer bot paddle.

Listing 6. Draw Everything

function drawNet() {
	for(var i=0;i<canvas.height;i+=40) {

function drawEverything() {
	// next line blanks out the screen with black

	if(showingWinScreen) {
		canvasContext.fillStyle = 'white';

		if(player1Score >= WINNING_SCORE) {
			canvasContext.fillText("Left Player Won", 350, 200);
		} else if(player2Score >= WINNING_SCORE) {
			canvasContext.fillText("Right Player Won", 350, 200);

		canvasContext.fillText("click to continue", 350, 500);


	// this is left player paddle

	// this is right computer paddle

	// next line draws the ball
	colorCircle(ballX, ballY, 10, 'white');

	canvasContext.fillText(player1Score, 100, 100);
	canvasContext.fillText(player2Score, canvas.width-100, 100);

We have created a function which draws a net at the center of the game area. It is a simple straight line inside the Canvas which will act as the net of the game. This net has no particular role in the game but it will separate the user's side and the computer bot's side.

Now let's create a function drawEverything that will draw the Canvas, paddles and the ball on the game area. It will also control the two different screens and display scores and messages whenever a player wins.

If the showWinScreen is set to true then it will check the score of both the players and whosoever has got the score more than the Winning Score, it will display the appropriate message. After the winning message has been displayed, we will also show whether the player wants to start a new game or not.

After this we are creating two different paddles by calling the colorRect function which we will create in the next section. This function will create both the paddles i.e for user and the bot and then we are creating a ball to play by calling a function colorCircle which we will also create in the next section. These above lines of code will create paddles, net and ball for the game. Let's now create two more functions i.e "colorCircle" and "colorRect".

Listing 7. Ball and the Paddle

function colorCircle(centerX, centerY, radius, drawColor) {
	canvasContext.fillStyle = drawColor;
	canvasContext.arc(centerX, centerY, radius, 0,Math.PI*2,true);

function colorRect(leftX,topY, width,height, drawColor) {
	canvasContext.fillStyle = drawColor;
	canvasContext.fillRect(leftX,topY, width,height);



In the above lines of code we are creating two different functions to draw paddles and ball on the screen. We are first selecting the color we want to fill and after that we are giving the coordinates on the Canvas where we have to draw the rectangle ( paddle ). Canvas already has a built-in function "fillRect" to draw a rectangle and with the help of this function we have created two paddle on the game screen. We have used a little bit of mathematics to draw a circle on the Canvas as there is no built-in method to draw a circle in HTML Canvas. After this we are closing the <script> and the <html> tag. Now our game is complete.

Here is a screenshot of the game:

Figure 1. Playing the game

Figure 2. Winning the game


In this article we have seen how to create a game with JavaScript using HTML5 Canvas. We have seen how we can use the DOM ( Document Object Model ) to draw rectangles and circles inside Canvas. We have created different events in JavaScript and learned how we can handle those events to make a complete game. Our JavaScript game is fully functional and if you want you can change the winning score to a different value. If you have any queries then feel free to start a discussion at the bottom of this page.

CODING is my Passion first, hobby second and job third! I am Full Stack Developer from last two years and I love building scalable web applications and modern websites with new technologies.I started with my web development with ...

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login