Javascript game development 6: graphics

After we draw some pixels, we should move forward to paint images. This is quite simple to do, because the html5 canvas has the functionality build in. I think it’s the best option to use the png file format. Because it’s lossless compressed and support alpha transparency.

The only thing we should think about is, how to load and manage our graphics? It’s enough to load every image file one time. We can set the position of objects over their vector and paint the image related to it. But more objects can be related to one image (or sprite, but later more to sprites). It doesn’t matter that we paint physically the same image data for multiple objects that looks the same.

So I did a new module with the name “graphic”. It loads all images (later animates sprites, too) and you can reach them from outside over this single module.

Use X and Y key (after focusing with a click) and move your mouse over it!
Result of this chapter

download chapter


window.modules.graphic = (function($) {
    return {
         *  all files to load 
         *  with php it would be possible to read the file system of the server
         *  so you could load an php over ajax that generate the paths
         *  and return that as json
         *  but we do pure js
        imageFiles: [
        images: {},
        init: (function() {
            //iterate every image, load and add it to the graphics.images object 
            $.each(this.imageFiles, function() {
                var image = new Image();
                image.src = "./graphic/" + this;
                //the name of the resulting object is the filename without ".png"
                var index = this.replace(".png", "");
                window.modules.graphic.images[index] = image;
//for example you add dwarf.png you got as image object:

Load the graphics module trough following changes on the index.html:

    name: "graphic",
    callback: (function() {

I’ve updated the screen.js with an method for painting images:

drawImage: (function(x, y, image) {
    this.ctx.drawImage(image, x, y);

The new main loop uses the smiley and man graphic and combine it with the input module (javascript game development 5 input).

You can control the scene with your mouse an the y and x key.

The new main.js:

window.modules.main = (function($) {
    return {
        //stores the horizontal position for second man graphic 
        manX: 0,
        loop: (function() {
            var modules = window.modules;
            var objects = window.objects;
            var mousePosition = modules.input.mousePosition();
            var i = mousePosition.x / 50;
            //y and x key controls the second man 
            else if(modules.input.isKeyDown(89))
            //move the smiley appending on the mouse position
                Math.sin(i) * 100 + 154,
                Math.cos(i) * 100 + 104,
                mousePosition.x - 24,
                mousePosition.y - 40,