JavaScript and HTML5 – Simple Game Creation Tutorial (part 1)

This is going to be a record of me learning to create a simple sprite based game with JavaScript and HTML5. I’m going to start with creating a simple single colored canvas with a “hero” sprite drawn onto it. Next we’ll add in the ability to control the hero character with the keyboard. Once that is working correctly I’ll move on to adding scenery and collision detection. Assuming all goes well up to that point, I’ll be adding in bad guys and then, hopefully, some fireballs (everything’s better with giant balls of fire!).

In HTML5 the base object we’ll be using for drawing to the screen will be the canvas. This element provides all of the methods we’ll need for drawing images, lines, etc onto the screen. Keep in mind when working with HTML5 that it uses a single doctype(as opposed to the multiple doctype options available in HTMl4). A good base HTML5 with a basic canvas element would look like the following:

[ccle_html]







Your browser does not support HTML5


[/ccle_html]

This sets us up with the the base doctype and provides a canvas element that we’ll be able to use to draw everything we need to the screen. When you add the canvas element to your page you can specify the width and height attributes if you want, I’m going to be setting those using JavaScript instead. I’m going to go ahead and download jQuery from the CDN and add a reference to it in order to make use of some of the methods it provides as well as a reference to a js file I’ll be creating to hold all my game logic into the head section of my html:

[ccel_html]


[/ccel_html]

One “trick” you can use when you are going to be using jQuery in your code (assuming you are using Visual Studio for your editing) is to download and add a reference to the jQuery vsdoc file for the version you are using. The vsdoc files are easily downloaded from the Microsoft CDN. Download that file and store it in the same location as your script file then, at the top of your script file, add a reference line like this to enable jQuery intellisense:

[ccel_javascript]
///
[/ccel_javascript]

The next steps will be to define and instantiate the global variables we’ll be using throughout the game tutorial. We’ll need an object to hold the canvas, one to hold the context (this is what we will actual be drawing onto), an object for the width and height of the game and, finally, one to hold our player. For now we’ll set the game area to be 800 x 600 and we’ll fill in the background with a dark green color. The code to do this looks like the following:

[ccel_javascript]
// Define the globals we’ll be using throughout the code
var canvas;
var context;
var gameW = 800;
var gameH = 600;
var hero = null;

$(window).load(function()
{
// retrieve a reference to the cavas object
canvas = document.getElementById(“mainCanvas”);
// create a context object from our canvas
context = canvas.getContext(“2d”);

// set the width and height of the canvas
canvas.width = gameW;
canvas.height = gameH;

// tell the context we are going to use a dark green fill color
context.fillStyle = “#004400”;
// fill the entire canvas with the color
context.fillRect(0, 0, gameW, gameH);
});
[/ccel_javascript]

The next step will be to create the sprite we’ll be using for our player character. Depending on the format you’ll be using for your game you’ll need to create different views of your sprite to represent the movements it is able to make. I’ve always been fond of the original Zelda game, so that’s the model I’ll be using for my sprites (I found this image in a folder from WAY long ago so I’m not sure if I created it or if I got it from someone else, if anyone knows the source for the images, please let me know):

Sprite to use for a simple mage character

The image consists of 8 32×32 sprites that provide two different sprites for each position (walking up, down, left, right). This allows us to provide a sprite animation to allow us to make the character look like it is walking around on the screen instead of just sliding everywhere. To work with the hero we’re going to go ahead and create a new JavaScript object type called hero. The object will need to house all of the important information about the hero character as well as the methods we need to draw it to the screen and move it around. Thinking about this at a high level we’ll need to know: The width and height of the hero, where it is on the screen, which arrow keys are being pressed by the player, what image / sprite we need to use when we render it and how often we update the sprite being used. That provides us with the main properties we’ll be using for the hero but we also need the methods to control what the hero can do. At the most basic level we just need to be able to draw the hero to the screen so we’ll add a render method to our hero object. The object so far looks like the following:

[ccel_javascript]
function heroObject()
{
// The width and height of the sprites for our hero character
this.width = 32;
this.height = 32;
// Place it at a random spot on the screen to start
this.x = this.width * Math.floor(Math.random() * (gameW / this.width));
this.y = this.height * Math.floor(Math.random() * (gameH / this.height));
// An array to hold the information about which keyboard keys are pressed
this.keys = new Array();
// When was the last time we drew the hero to the screen
this.lastRender = Date.now();
// What delay do we want to use between switching sprites (in milliseconds)
this.animSpeed = 250;
// What image are we using for the hero
this.image = new Image();
// Which sprite in the image are we currently rendering
this.whichSprite = 0;

this.render = function()
{
// drawImage takes for parameters:
// the image to draw
// the x and y coordinates to use from the source image
// the width and height to use from the source image
// the x and y coordinates to draw it to on the canvas
// the width and height to draw it into on the canvas
context.drawImage(this.image, this.whichSprite, 0, this.width, this.height, this.x, this.y, this.width, this.height);
};
}
[/ccel_javascript]

We’ll need to place this function in the JavaScript code above the [cciel_javascript]$(window).load(function()[/cciel_javascript] function in order to make use of it properly (you need to define your objects before you make use of them in scripting languages). And then we’ll add the code into the [cciel_javascript]$(window).load(function()[/cciel_javascript]function to create the hero, set its image and draw it to the screen. We’ll be using the image.onload functionality in order to make sure we don’t try to draw the hero on the screen prior to the image being loaded. To do these steps, at the bottom of the [cciel_javascript]$(window).load(function()[/cciel_javascript] add in the following:

[ccel_javascript]

// instantiate a heroObject
hero = new heroObject();
// set its image to the proper src URL
hero.image.src = “images/Mage_Sprite.png”;
// once the image has completed loading, render it to the screen
hero.image.onload = function()
{
hero.render();
};
[/ccel_javascript]

At this point you’ll have a green canvas element and each time you refresh the screen the hero character will appear at a random spot within the game grid looking something like this:

Simple Game 1 - Sample Image

Here’s the link to the demo for this code

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.