A simple HTML5 Game tutorial – Part 1

I’ve always wanted to create a game. It seems the older I get the closer I get. This post is the first in a small series which walks you through the steps I followed to create a simple game. Here is a taster of the end result:

A simple game create using HTML's canvas and JavaScript
Screenshot of HTML5 game

If you want to have a peek at the result of following this post click here.

Goals

When I started this mini-project my main goals were:

  1. Create the ‘bad guys’.
  2. Ensure the ‘bad guys’ move in a random pattern; but, stay within the bounds of the screen.
  3. Allow a player to shoot the ‘bad guys’ by moving a target controlled by the mouse.
  4. Keep a tally of how accurate the player is e.g. shots / hits ratio.

Tools & Technology

The game uses the following technologies:

  1. HTML5 – Specifically the Canvas feature
  2. CSS
  3. JavaScript

The Implementation

The first step is to create a blank HTML page which contains a single canvas object.

<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
HTML5 Canvas Game
    <style>

	#canvas {
	    position: absolute;
	    top: 0px;
	    left: 0px;
	    cursor: none;
	}

    </style>
</head>
<body>
    <canvas id="canvas" width="1000" height="600"></canvas>
</body>
</html>

The above HTML includes the bear minimum to create a page with a single canvas element with its id attribute assigned to ‘canvas’. The CSS in the header then simply targets the canvas element by its id and positions it at the top left of the screen using position absolute. The initial width and height are set to 1000 by 600 pixels via the elements size attribute. I require the height and width to fill the bounds of the browser. To achieve this we need to control these size attributes within JavaScript. The code written needs to initially set the height and width of the canvas once the page has loaded. And, secondly to resize the canvas follownig a change in the browser’s window.

Controlling the canvas’ size is achieved with the following JavaScript:


	var ctx = null;
	var canvas = null;

	function init() {

	   canvas = document.getElementById('canvas');
	   ctx = canvas.getContext('2d');
	   resizeCanvas();
	}

	function resizeCanvas() {

	   ctx.canvas.width = window.innerWidth;
	   ctx.canvas.height = window.innerHeight;

	}

	// resize the canvas to fill browser window dynamically
	window.addEventListener('resize', resizeCanvas, false);

	// Start the init function on page load
	window.onload = function() {
	   init();
	};

Now we’ve ensured the canvas is maximized to fully fill the browser the next step is to draw some ‘bad guys’. For this we need a image for each bad guy. Choosen by my son we have the following bunch of misfits.

html5-game-bad-guys

To make the game interesting we require lots of ‘bad guys’ and each needs to start in a random position and begin to move in a non-predictable way. These requirements drive how we put this into action. As we need lots of ‘bad guys’ in programming terms this translates into we need an array of objects. Each of these object represent a ‘bad guy’ which needs to know its position, speed and direction of movement. To handle this I created an object called a ‘Thing’.


	function Thing(mapX, mapY, x, y, canvas) {
	   this.x = x;
	   this.y = y;
	   this.mapX = mapX;
	   this.mapY = mapY;
	   this.height = 50;
	   this.width = 50;
	   this.direction = Math.floor((Math.random()*359));
	   this.speed = Math.floor((Math.random()*50) + 5);
	   this.canvas = canvas;
       };

	Thing.prototype.draw = function(ctx, sprite) {

	    ctx.drawImage(sprite, this.mapX, this.mapY,
		90, 90,
		this.x, this.y,
		this.width, this.height);

	};

Now we have an object the represents each of the ‘bad guys’ we need to create the array which holds them. We can then use this array within the game to iterate through each object, allowing us to draw the object. Prior to creating the array we first need to load the sprite image:


	function loadSprite() {

	    sprite = new Image();
	    sprite.src = 'sprite.png';

	}

To initialise the array we do the following:


	function createThings() {

	    var i;

	    spriteMap =  [
		[0, 120], [140, 120], [270, 120] ,[270, 250],
		[400, 120], [400, 250], [530, 250], [530, 120]
	    ];

	    for(i = 0; i < 10; i++) {
		sprites.push(createThing(spriteMap));
	    }
	}

This function simply creates an array called ‘spriteMap’. It holds the location of each of the ‘bad guys’. Each having a different image taken from the sprite. The for statement repeats ten times. Each time the sprite map is then passed into the ‘createThing’ function. It is this function that creates a new thing object:


	function createThing(spriteMap) {

	    var cur, map = spriteMap[Math.floor(Math.random() *
			    (spriteMap.length - 1))];

	    cur = new Thing(
		map[0],
		map[1],
		Math.floor((Math.random()*canvas.width)+1),
		Math.floor((Math.random()*canvas.height)+1),
		canvas
	    );

	    return cur;
	}

The function consists of three lines of code. The first line declares two variables. The first is used to hold the new Thing object. The second is used to hold the location of the image which will be used to draw the Thing. This is determined by asking for a random number which is used to extract the sprites location within the sprite map. The second line of code then creates the object. The Thing object expects four parameters to be passed to its constructor. These are the X and Y position of the sprite within the map and the X and Y position the Thing will start at. The later pairing is again set using the inbuilt random function. The final line of code returns the object to the calling interface. The object is then stored in the array called sprites.

We’re now at a point were we can start the game. Therefore, we need to draw each of the items within the sprites array onto the canvas:

Earlier we added a draw function to the Thing object, thus, we simply iterate through the array and tell each Thing to draw itself onto the Canvas.


	    for(i = 0; i < sprites.length; i++) {
		sprites[i].draw(ctx, sprite);
	    }

Putting the above together results in the following code:

<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>Canvas Rocks</title>
    <style>

	#canvas {
	    position: absolute;
	    top: 0px;
	    left: 0px;
	    cursor: none;
	    background-color: black;
	}

    </style>
</head>
<body>
    <canvas id="canvas" width="1000" height="600"></canvas>
    <script>

	function Thing(mapX, mapY, x, y, canvas) {
	   this.x = x;
	   this.y = y;
	   this.mapX = mapX;
	   this.mapY = mapY;
	   this.height = 50;
	   this.width = 50;
	   this.direction = Math.floor((Math.random()*359));
	   this.speed = Math.floor((Math.random()*50) + 5);
	   this.canvas = canvas;
       };

	Thing.prototype.draw = function(ctx, sprite) {

	    ctx.drawImage(sprite, this.mapX, this.mapY,
		90, 90,
		this.x, this.y,
		this.width, this.height);

	};

	var ctx, canvas, sprites = [], sprite = null;

	function loadSprite() {

	    sprite = new Image();
	    sprite.src = 'sprite.png';

	}

	function createThings() {

	    var i;

	    spriteMap =  [
		[0, 120], [140, 120], [270, 120] ,[270, 250],
		[400, 120], [400, 250], [530, 250], [530, 120]
	    ];

	    for(i = 0; i < 10; i++) {
		sprites.push(createThing(spriteMap));
	    }
	}

	function createThing(spriteMap) {

	    var cur, map = spriteMap[Math.floor(Math.random() *
			    (spriteMap.length - 1))];

	    cur = new Thing(
		map[0],
		map[1],
		Math.floor((Math.random()*canvas.width)+1),
		Math.floor((Math.random()*canvas.height)+1),
		canvas
	    );

	    return cur;
	}

	function init() {

	   canvas = document.getElementById('canvas');
	   ctx = canvas.getContext('2d');
	   resizeCanvas();
	   loadSprite();
	   createThings();
	}

	function start() {
	    for(i = 0; i < sprites.length; i++) {
		sprites[i].draw(ctx, sprite);
	    }

	}

	function resizeCanvas() {

	   ctx.canvas.width = window.innerWidth;
	   ctx.canvas.height = window.innerHeight;

	}

	// resize the canvas to fill browser window dynamically
	window.addEventListener('resize', resizeCanvas, false);

	// Start the process
	window.onload = function() {
	   init();
           setTimeout(start, 100);
	};

    </script>
</body>
</html>

We now have a initial skeleton of a game; except, it’s not very exciting. We need some movement and a way to shoot the ‘bad guys’ we’ll tackle this in part 2. For now we have the following:

A simple game create using HTML's canvas and JavaScript
Part one of my HTML5 game walk-through

Putting all the above together achieves our first objective which can be viewed here. In Part 2 we’ll tackle our second objective.

Advertisements

4 thoughts on “A simple HTML5 Game tutorial – Part 1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s