Loading Gif

Create a HTML5 game tutorial – Part 1


Part 1 - General setup and moving a target accross a screen

This is part 1 of a set of tutorials that will hopefully give you an insight of how to go about creating a HTML5 game.

This tutorial came about as my brother wanted to piss off his mate by creating a game where you have to shoot sausages at his head! He’s from Cumberia you see. So it makes perfect sense.

Anywho my brother cant make games so long story short he asked me… and I thought it would be pretty funny. So I agreed to do it on the basis that it also might make some pretty good blog posts. Here is the first of those posts.

Skip to the example

The intro bit…

The term “HTML5 Game” could mean a multitude of things. It could be referring to the Canvas tag ( <canvas></canvas> ) using its 2Dcontext and WebGL or the like. Alternatively it could be referring to SVG (scalable vector graphics) which can be animated and scaled to any size without pixelating. But in this case its referring simply to the manipulation of the DOM using Javascript.

In this first post I will show you how to set up the game model and how to move a target across a screen. Please not that code will change as we go through the tutorial parts so the code shown here may not be the code that is used in the final outcome. Also this may not be the best way to create a game of this type. Its simply an experiment for fun and pushing modern browsers to the limit of what they are meant to do.

Creating The Game Object

So first things first we will create the game object. The basic structure of this will look a little like the below…

So this initial game object structure will allow us to call our draw and update functions at 60 frames per second. If we want to speed the game up then we can increase the game.fps value to something higher and vice versa for a slower game. At this point for simplicities sake we are using setTimeout() to create the tick. Eventually we will update that to the far superior requestAnimationFrame api.

If you were to run this in your browser right now nothing would happen. That is because we have yet to kick off the game by calling game.init . So we will do this now. Im going to be using jQuery to create the majority of this game so after adding the latest version of jQuery to your html file add this little snippet of code to init the game once the document has loaded.

Now open your browser… and… you will see nothing. So far we have not styled our game at all or created a canvas. If you open the console however, you should see the words “updating” and “drawing” being logged over and over again. This means its working. :)

Creating the canvas and making it fill the screen

Next we will create a <div> to use as a canvas or holder for our game and make it fill the screen. Firstly open your html document and add <div id="game"></div> Then open up your css file and add the following…

Now if you reload your page you will hopefully see that the screen has gone from white to dark grey. This means we now have a full screen game canvas. If not don’t worry as we will also be adding some javascript to set the size of the canvas. Go back to our js game object and add the following functions…

The purpose of the “setSize” function is to set the size of the game to the size of the window. It does this be getting the window height and width and then setting the css of the game canvas to the same size, so at any point we can call game.setSize() and the game will become the width and height of the screen.

We also added the two functions “resize” and “afterResize”. The resize function will be called every time the window is resized and the afterResize function will be called 500milliseconds after the user has finished resizing. There is a detailed explanation about how the “afterResize” function works here. We will use “afterResize” for most of our functions as it speeds up the game and involves much less calculation on the browsers part.

For all this to work we still need to modify our game.init function as currently we are not calling any of these new functions and the game object has no way of interacting with our <div id="game"></div> . We will do this by adding the following to our init function.

You will notice we have now added the new function calls to our init function. game.resize() will now be called on window resize which will then trigger game.afterResize and game.setSize . We also now set the game size on initiation of the game and have added a way to pass a selector to our game object that will work as the games container or canvas. Just one little update to our js file and the new functions should start to work.

Adding and animating the moving target

Now that the game canvas mirrors the window size and we have working draw and update functions we can add our first moving object. The first object we will add in this game is the target. (which will eventually be my brothers mates head). We will use a fairly standard HTML div for that.

Firstly to add the div to the page we will first modify our game object. Add the following to your game object. Just below the game.fps line.

Then add this to your CSS to make the target appear as a red box 100px square.

This created a div object with the id of “target” and added some styling rules for it, but we have now yet added the target to the page. To add the target to the page add this simple line to the game.init function just underneath the game.canvas = ... line.

Now refresh the page. If everything want well you should see a red 100px by 100px div in the top left corner of your game.

There’s one problem though…

Tty resizing the window. We want everything to scale on window resize but currently the div is fixed at 100px by 100px. Now this is not something a normal HTML page does well. But it can be done and it dosn’t even require javascript. We can do it in pure CSS by using the old height:0px and padding trick.

Amend your CSS for the #target div to the following…

This is a weird hack that resizes the target to 10% of the width or the screen but also maintains aspect ratio which is very important for our game. Try changing the height to 10% and removing the padding. You will notice that the target is now 10% of the width or the screen and 10% of the height of the screen. Which will result in a rectangle and not our perfectly formed resizing square.

So now all that’s left is to animate the target. We do this with the “draw” and “update” functions. All collection of positions and calculations about where elements should be should be done in the “update” function and all moving of elements and updating the DOM should be done in the “draw” function. This will keep the game running smoothly as the browser only has to “draw” the DOM once per frame. This is know as “reflow” or “redraw” and you can learn more here.

We want the target to move left until it hits the right edge of the game and then flip the animation so the target moves right until it hits the left edge of the game and roughly be vertically centred. We achieve this by calculating the left value of the targets css and changing the targets dir property based on this value. We then either plus or minus the targets speed (in pix) based on the dir value.

First we have to add the target speed to the game object…

Then we add the following the the games update function…

So here we calculate the y position based on half the game window height minus half the target height. This vertically centres the target. The x position is calculated by adding or subtracting the speed based on the direction.

The above will not actually animate the target. This is done in the “draw” function. The “update” function just adds the property “pos” to the target. which can be accessed using game.target.pos we will use this property in the “draw” function to actually update the targets position.

In the draw function we just need to update the css of the target to the newly calculated positions by adding the below js.

And voila! We have the beginings of a working game. So far we have:

  • a game canvas running at 60fps
  • a game that resizes to the current window size
  • a target that animates back and forth across the game screen

Next time…

Next time we will learn how to add a projectile (sausage) and fire it at the target we created.

See below for a working example of the code written in this example.


Part 1 - The finished code in action

Download files Open in a new window