- Tutorials / JavaScript
- Saturday, 14th Jan, 2012
Home » Tutorials » JavaScript » Most Easiest & Simplest Way to Create a Game Using HTML5 Canvas
In this tutorial, we are going to create a squash game using HTML5 technology – Canvas. If you are new to canvas, please be sure to read the “HTML5 Canvas For Absolute Beginners – Part 1” before you proceed.
Let’s start our tutorial by creating a HTML document with official HTML5 document type:-
<!DOCTYPE html>
This is to tell your browser that, this is the latest version of HTML document with canvas supported.
Next, we create a canvas with an id “gameBoard”, width, height defined and place it inside the body tag as shown below:
<canvas id="gameBoard" width="300" height="300">
The JavaScript is the backbone of the game and it consist of a collection of global variables and 3 functions. First, let’s discuss about the variables:
// Global variables. var ballX = 150; var ballY = 150; var ballDX = 2; var ballDY = 4; var boardX = 300; var boardY = 300; var racquetX= 150; var racquetH= 10; var racquetD = boardY - racquetH; var racquetW = 150; var canvas; var ctx; var gameLoop; var titleFontSize = "bold 24px Georgia"; var contentFontSize = "normal 12px Arial";
Next step is to write a function to draw the game canvas for us.
function drawGameCanvas() {
canvas = document.getElementById("gameBoard");
if (canvas.getContext) {
ctx = canvas.getContext("2d");
gameLoop = setInterval(drawBall, 16);
window.addEventListener('keydown', whatKey, true);
}
}
Create a variable called ‘canvas‘ in the function of drawGameCanvas, assigned it to hold the canvas object, so you can access the canvas object easily. Check the visitor’s browser, if their browser is supporting canvas technology, then you have to define the canvas type to 2D, create a interval to run a function called ‘drawBall‘ that draw the ball in every 16 milliseconds. Finally, create an event listener of keydown at the end of the function, to allow visitor to play the game using keyboard.
function drawBall() {
// Clear the board.
ctx.clearRect(0, 0, boardX, boardY);
// Fill the board.
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.rect(0, 0, boardX, boardY);
ctx.closePath();
ctx.fill();
// Draw a ball.
ctx.fillStyle = "maroon";
ctx.beginPath();
ctx.arc(ballX, ballY, 15, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
// Draw the racquet.
ctx.fillStyle = "green";
ctx.beginPath();
ctx.rect(racquetX, racquetD, racquetW, racquetH);
ctx.closePath();
ctx.fill();
// Change the ball location.
ballX += ballDX;
ballY += ballDY;
// Bounce on a left or right edge.
if (ballX + ballDX > boardX - 15 || ballX + ballDX < 15) ballDX = -ballDX;
// If ball hits the top, bounce it.
if (ballY + ballDY < 15) ballDY = -ballDY;
// If the ball hits the bottom, check see if it hits a racquet.
else if (ballY + ballDY > boardY - 15) {
// If the ball hits the racquet, bounce it.
if (ballX > racquetX && ballX < racquetX + racquetW) ballDY = -ballDY;
// Otherwise the game is over.
else {
clearInterval(gameLoop);
ctx.font = titleFontSize;
ctx.fillStyle = "red";
ctx.fillText("Game Over", 80, 130);
ctx.font = contentFontSize;
ctx.fillStyle = "blue";
ctx.fillText("Please refresh the page to replay", 55, 150);
}
}
}
This function is called by the drawGameCanvas function every 16 milliseconds:
function whatKey(evt) {
switch (evt.keyCode) {
// Left arrow.
case 37:
racquetX = racquetX - 20;
if (racquetX < 0) racquetX = 0;
break;
// Right arrow.
case 39:
racquetX = racquetX + 20;
if (racquetX > boardX - racquetW) racquetX = boardX - racquetW;
break;
}
}
The whatKey function listen to the key press and determine the direction of the racquet for us.
Finally, initial the function of drawGameCanvas via the body tag as shown below:
<body onLoad="drawGameCanvas()">
That’s all, save your document, view it in browser with canvas supported and enjoy it!
<!DOCTYPE html>
<head>
<title>Squash Game Using HTML5 Canvas | onlyWebPro.com</title>
<script type="text/javascript">
// Global variables.
var ballX = 150; // Ball x position.
var ballY = 150; // Ball y position.
var ballDX = 2; // Change in ball x position.
var ballDY = 4; // Change in ball y position.
var boardX = 300; // Board width.
var boardY = 300; // Board height.
var racquetX = 150; // Initial racquet location.
var racquetH = 10; // racquet height.
var racquetD = boardY - racquetH; // racquet depth.
var racquetW = 150; // racquet width.
var canvas; // Canvas element.
var ctx; // Canvas context.
var gameLoop; // Game loop time interval.
var titleFontSize = "bold 24px Georgia";//Set title font size
var contentFontSize = "normal 12px Arial";//Set content font size
// This function is called on page load.
function drawGameCanvas() {
// Get the canvas element.
canvas = document.getElementById("gameBoard");
// Make sure you got it.
if (canvas.getContext) {
// Specify 2d canvas type.
ctx = canvas.getContext("2d");
// Play the game until the ball stops.
gameLoop = setInterval(drawBall, 16);
// Add keyboard listener.
window.addEventListener('keydown', whatKey, true);
}
}
function drawBall() {
// Clear the board.
ctx.clearRect(0, 0, boardX, boardY);
// Fill the board.
ctx.fillStyle = "yellow";
ctx.beginPath();
ctx.rect(0, 0, boardX, boardY);
ctx.closePath();
ctx.fill();
// Draw a ball.
ctx.fillStyle = "maroon";
ctx.beginPath();
ctx.arc(ballX, ballY, 15, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
// Draw the racquet.
ctx.fillStyle = "green";
ctx.beginPath();
ctx.rect(racquetX, racquetD, racquetW, racquetH);
ctx.closePath();
ctx.fill();
// Change the ball location.
ballX += ballDX;
ballY += ballDY;
// Bounce on a left or right edge.
if (ballX + ballDX > boardX - 15 || ballX + ballDX < 15) ballDX = -ballDX;
// If ball hits the top, bounce it.
if (ballY + ballDY < 15) ballDY = -ballDY;
// If the ball hits the bottom, check see if it hits a racquet.
else if (ballY + ballDY > boardY - 15) {
// If the ball hits the racquet, bounce it.
if (ballX > racquetX && ballX < racquetX + racquetW) ballDY = -ballDY;
// Otherwise the game is over.
else {
clearInterval(gameLoop);
//alert("Game over!");
ctx.font = titleFontSize;
ctx.fillStyle = "red";
ctx.fillText("Game Over", 80, 130);
ctx.font = contentFontSize;
ctx.fillStyle = "blue";
ctx.fillText("Please refresh the page to replay", 55, 150);
}
}
}
// Get key press.
function whatKey(evt) {
switch (evt.keyCode) {
// Left arrow.
case 37:
racquetX = racquetX - 20;
if (racquetX < 0) racquetX = 0;
break;
// Right arrow.
case 39:
racquetX = racquetX + 20;
if (racquetX > boardX - racquetW) racquetX = boardX - racquetW;
break;
}
}
</script>
</head>
<body onLoad="drawGameCanvas()">
<canvas id="gameBoard" width="300" height="300"></canvas>
</body>
</html>
PHP: Object Oriented Programming for Absolute Beginners
HTML5 Canvas For Absolute Beginners – Part 4
Introduction To Device Orientation With HTML5
CSS3: Spinner Animation
Solving CSS Float's Problem
Create Facebook App Style Slide-Out Navigation
Build Intelligent Layout Using CSS Calc() Property
Catch It!
Make A jQuery Sticky Header In 5 Minutes
Koubachi Web Game
HTML5 Brain Challenge - Maths Edition