Tutorial: HTML 5 Space Shooter Part 1

Happy new year! 2011 was a fantastic year for me and I hope it was for you as well; hard to believe 2012 is here already! I figured a new tutorial would be a great way to start off the year so here you go: part 1 in a series on creating an HTML 5 shooter using EaselJS!

If you want to see the end result, use Google Chrome and go here. We'll take it easy in part 1 and just set up a moving starfield that will ultimately serve as the background for our game.

To get started, create a directory for the project and inside there, a blank html file. Then download EaselJS from github. Once downloaded, unzip the package and grab the easel.js file from the lib directory; this is a compressed version of the library that we're going to use. For simplicity, put the easel.js file into the same directory as your html file.

Now it is time to set up the html page. We'll start with the basics:

<!doctype html>


        <title>HTML 5 Shooter</title>


    <body onload="init();" style="background-color:#001132;">

        <div id="wrapper" style="width:640px; height:480px; 
                 margin-left:auto; margin-right:auto; 
                 background-color:#000; border:5px ridge #cc8811">

	    <canvas id="canvas" width=640 height=480 
                    style="margin-left:auto; margin-right:auto;">




In the code above, all we've done is outline a basic html page and added some specific styling information to center the content and provide a nice border around the game area. We also told the body tag to call a javascript function, init, once it loads (though we have not yet wrote this function). In addition, we gave id names to our wrapper div and the canvas elements so that we can easily access them from JS.

One thing to note here, you'll see that I added the width and height of the wrapper inside the style attribute, but on the canvas div, it is outside of it. I initially was setting the canvas width and height inside the style attribute as well, but this caused problems and the content wouldn't be centered. I'm not sure why that makes a difference, but it does. So just a head's up about that!

Next, we'll create a couple of script tags. One will reference the easel.js file and one will contain our custom code. Add the following lines just below the title tag.

<script type="text/javascript" src="easel.js"></script>

<script type="text/javascript">


Alright, with the basic set up out of the way, it's time to get down to business! In the next step we're going to add a few useful variables and also create the init function that we're telling our body tag to call. Add the following lines to the empty script tag we created above:

var stage;
var canvas;
var g;  
var stars;

function init() {
    canvas = document.getElementById("canvas");
    stage = new Stage(canvas);



What have we got going on here? Well, first we're declaring a few variables. One will hold the stage instance, one will hold a reference to our canvas object, the g variable will contain a graphics object and stars will be an array in which we store... well... stars!

Inside the init function we grab our canvas reference and then create a new Stage object, passing the canvas in as a parameter. The Stage object is specific to easelJS and provides a familiar API for Flash developers.

After that we're making a call to a function named createStarField which we will create in the next part. Finally we set our desired framerate using the Ticker object in easelJS. Not so bad, eh?

Ok, now let's make that createStarField function. We'll put this function just after the init function. We're also going to create a helper function: randRange. This function will give us a random value between two numbers.

function createStarField() {		
	stars = new Array();
	g = new Graphics();
	g.drawCircle(0,0, 1);
	for(var i = 0; i < 100; ++i) {
        var s = new Shape(g);
	    s.x = randRange(10, 630);
	    s.y = randRange(-250, 470);
	    s.scaleX = randRange(0.5, 2);
        s.scaleY = s.scaleX;
	    s.alpha = Math.random() + 0.2;

function randRange(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;

Let's break down what we just did here. In the createStarField function, we first make a new array to hold our stars. The next thing we do is make a new graphics object. Like Stage and Ticker, this is a special easelJS object. We set the stroke and fill color to white using the getRGB method of the Graphics object. Then we draw a circle with an x and y of zero and a radius of one.

With the Graphics object ready to roll, we do a standard for loop and create our stars. We make a star by creating a new Shape object and passing in our Graphics object, g. As you might have guessed, Shape is yet another easelJS object. We then add the newly created star to our stars array.

Next we use our helper function, randRange, to assign our star a random starting position. Then we use it again to give our stars a random size and alpha value because it would be boring if they were all the same! Lastly, we add the star to the stage using stage.addChild.

We're just about done, but not quite! We need to move the stars and make the display update! We'll do this by creating a couple of new functions. One we'll call tick, you can think of this as the equivalent of an enter frame function from Flash. This function works in conjunction with the easelJS Ticker object and MUST be named tick. The other will be called updateStarField and will be responsible for moving the stars.

First, we'll register our window with the Ticker object to make sure our tick function gets called each frame. Add the following line to the end of the init function.


Easy enough, right? Now we need to define our tick and updateStarField functions.

function tick() {

function updateStarField() {
    var curStar;
    var limit = stars.length;
    for(var i = 0; i < limit; ++i) {
        curStar = stars[i];
	    curStar.y += 4;
	    if(curStar.y > 480)
            curStar.x = randRange(10, 630);
	        curStar.y = -randRange(20, 450);					

Now we're cookin' with gas! The tick function is easy, we just make it call our updateStarField method and tell the stage to update. Of course, updateStarField is pretty simple too, right? All we do is loop through our stars array and update each star's y position by adding 4 to it. We then check to see if the star's y position is greater than our stage height (480). If it is, then we simply reset the star to a new position at the top of the stage (note the negative sign before the second call to randRange).

Well, if you followed along you should now have a scrolling starfield in an html page! Pretty cool! If you ran into trouble, you can grab the files below and see if you've missed something.

In the next part, we'll add a player ship and movement! Thanks for reading and feel free to post feedback; I'm new to HTML and JS development myself so if you see something that could be done better, let me know!

Download Source

Part 2 >

Bookmark and Share

Leave a Reply

Subscribe to RSS feed FGS5 Badge