Click here to Skip to main content
15,884,628 members
Articles / Web Development / HTML

Beginning HTML5 Game Development

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
24 Feb 2012CPOL3 min read 18.4K   7   1
Introduction to HTML5 game development.

Goals:

  • Learn to use the <canvas> tag.
  • Learn to separate logic to separate source files.
  • Setup a basic game loop.

One thing I never liked about programming tutorials is that most are derived from some completed project. Now there’s nothing particularly wrong with this other than the author doesn’t take the time to provide a well documented skeleton to work from, something free of the bloat code specific to their game. They’ll leave in their classes and their draw code, but really I feel that code would be best placed in its own tutorial explaining how to build that game. So what this tutorial aims to provide is a bare minimum code base for you to build on.

We’ll start off with the <canvas> tag.

XML
<div align="center">
        <canvas id="canvas" width="800" height="600">
        Canvas not supported. :(
        </canvas>
</div>

This will place a 800 x 600 canvas in the center of the screen. The “id” option is important as it is the name your JavaScript files will use to interface with it. The text between the <canvas> tag can be replaced with anything you want displayed in the result that the user’s browser does not support HTML5.

The canvas is pretty pointless if you can’t draw to it, so create a JavaScript file for your game (mine’s called xong.js). We’ll need our page to be able to call the script, so let’s include it in the header.

XML
<script src="Xong.js"></script>

Now your variables and class definitions are part of the global namespace for the page. As far as I know, there is no way to house your code into different namespaces so be careful naming your variables, functions, etc across multiple files; defining a variable named X in one file, and then naming a variable X in another file, will produce weird results when including both files.

Let’s look at a basic game loop to place in your js file.

JavaScript
var _canvas = null;
var _buffer = null;
var canvas = null;
var buffer = null;

function Game(){
    this.gameLoop = null;
    var self = this;
    
    this.Init = function(){
        _canvas = document.getElementById('canvas');
        if (_canvas && _canvas.getContext){
            canvas = _canvas.getContext('2d');
            
            _buffer = document.createElement('canvas');
            _buffer.width = _canvas.width;
            _buffer.height = _canvas.height;
            buffer = _buffer.getContext('2d');
            
            buffer.strokeStyle = "rgb(255, 255, 255)";
            buffer.fillStyle = "rgb(255, 255, 255)";
            buffer.font = "bold 25px sans-serif";
        }
    }
    
    this.Run = function(){        
        if(canvas != null){
            self.gameLoop = setInterval(self.Loop, 50);
        }
            
    }
    
    this.Update = function(){
        // Update Objects
    }
    
    this.Draw = function(){
        buffer.clearRect(0, 0, _buffer.width, _buffer.height);
        canvas.clearRect(0, 0, _canvas.width, _canvas.height);
        
        //Draw Code
        canvas.drawImage(_buffer, 0, 0);
    }
    
    this.Loop = function(){
        self.Update();
        self.Draw();    
    }
}

This is pretty long so I’ll explain it chunk by chunk. At the top we have 4 variables. The first two are interfaces (the canvas interface and buffer interface) and the second two are the variables you’ll use to actually interact with the canvas context and buffer context.

Next we define a class called Game. If you are new to JavaScript as I am, the “everything’s a function” concept might be a little confusing in the beginning. Inside the class we have two variables and five functions. The gameLoop variable holds the game loop once we set it to run at a set interval, I’ll explain this in a bit.

The Init function should be called before you call Run; it sets up the canvas, buffer, your objects, etc. First it grabs the canvas context from the page by its id. Next we make sure it successfully accomplished this and can interface with the canvas. We store the context into the canvas variable and do the same steps for our screen buffer, making sure to make it the same size. Last we can set up some options for the buffer such as font, fillStyle (aka the color for filled primitives), and strokeStyle (the color for empty primitives).

The Run function is pretty simple. If the canvas was loaded successfully, we set the Loop function to be called every 50 milliseconds. We keep this stored in a variable, sort of like a thread.

The Update function is where you… update your game logic.

Draw doesn’t need too much explanation. First we clear the buffer and canvas, then we draw things to the buffer, and finally we draw the buffer to the canvas.

Last we have the Loop function which simply calls the Update and Draw functions.

The last step is to put it all together.

XML
<div align="center">
        <canvas id="canvas" width="800" height="600">
        Canvas not supported. :(
        </canvas>
        <script type="text/javascript">
            var play = new Game();
            play.Init();
            play.Run();
        </script>
</div>

We add a script block after the canvas is created. We instantiate the Game class, call the Init function, and the call the Run function. That’s it! The skeleton is complete. It won’t do anything yet but it’s easy to Google some draw code to place in your loop to test it out. Next time I’ll be posting tutorials on input, sound, and drawing. Hope you found this informative and feel free to leave me some feedback. ^^

Download Source: Skeleton.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader DejaMi Inc.
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
NewsResource of game dev Pin
ZenvaDEV20-May-12 6:25
ZenvaDEV20-May-12 6:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.