Simple Way To Make A Game Using HTML5 Canvas

Simple Way To Make A Game Using HTML5 Canvas

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.

View Demo

Getting Started

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 Backbone of Game

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";
 

  • ballX and ballY are the variable that holds the value of initial position of the ball.
  • ballDX and ballDy used to defines the distance of changes of the ball.
  • boardX and boardY defines the width and height of the game.
  • racquetX used to defines the initial position of the racquet (coordinate point start from top left).
  • racquetH defines the absolute height of the racquet.
  • racquetD is the initial y position (from top left) of the racquet.
  • racquetW is the width of the racquet.
  • titleFontSize defines the font size of the title in the game.
  • contentFontSize defines the font size of the title in the game.
  • canvas, ctx, and gameLoop created for global access.

Draw Game Canvas Function

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.

Draw Ball Function

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:

  • Clear the game canvas every time, when the function run using ctx.clearRect
  • Define the size, color and x, y position of the game board, ball and racquet.
  • Animate the ball’s x, y position by adding ballDX and ballDY, which we defined earlier.
  • If the ball hits the left or right edge, the ball ballDX value is reversed, which will make it bounce in the opposite direction.
  • If the ball hits the top edge, the ball ballDY value is reversed, which will make it bounce in the opposite direction.
  • If the ball hits the bottom, a check is made to see if it hit the racquet. If it did, then the ball is bounce back, else the game is over.

whatKey Function

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.

Init the Function When Page is On Load

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!

View Demo

Get the Code

<!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>
SOURCE

More to read:
jQuery Timeline Animation
iPhone Style Radio and Checkbox Switches using jQuery and CSS
Creating a “Filterable” Portfolio
Creating a Dynamic Poll with jQuery and PHP
SHARE US ON:
Facebook Twitter
Freemarket.com Marketplace

Explore/Tags

Tutorializing.com © 2014 by www.TheBrightBox.com