Javascript game development 2: screen

My idea is to involve you in the process of making a game. Maybe it would have been better to begin wit this chapter, but anyways. After I explained a way to organize javascript code, we can use this for an practical example. So will make an screen object that manages it self.
Because we need only one screen, we would maybe do good to solve this with a singleton pattern. But in Javascript we can simply create an object with “{}”, so there’s no constructor and you can’t make instances of it. I call this type of object “module”. The difference to an object that I handle under “object”, is that an object can be instanced with new.

So the folder structure looks at time like:

|-- object
|-- module
|-- screen.js

Result of this chapter

download chapter


<!doctype html>
    <script src=""></script>
    (function($) {
        //object that holds all modules
        window.modules = {};
        //define modules paths and callback functions
        var modules = [{
            name: "screen",
            callback: (function() {
                window.modules.screen.init(320, 240);
        $.each(modules, function() {
            var module = this;
            $.getScript("./module/" + + ".js",
                function() {

The index.html is a html document with the html5 doctype and utf-8 character coding. It includes the jQuery framework.
Like in explained here “javascript plugin system“, the modules are loaded asynchrony over AJAX. After any loaded script, the previous defined callback function is executed. In case of the screen, its initialized and filled up with red color.


window.modules.screen = (function($) {
    return {
        init: (function(w,  h) {
            this.width = w;
            this.height = h;
            //create canvas and get the dom object with .get(0) from the jQuery object
            this.canvas = $('<canvas width="' + w + '" height="' + h + '">').get(0);
            this.ctx = this.canvas.getContext("2d");
            //append it to the body
        fill: (function(color) {
            this.ctx.rect(0, 0, this.width, this.height);
            this.ctx.fillStyle = color;

In the screen.js file, a closure returns an object and attach it to the “window.modules” object. So it can be found at any place in the code. It has two methods:

  • init: creates an canvas in given dimensions an append it to the body
  • fill: fill the canvas with the given color