Vanilla JS Tutorials

JsIso Tutorials

RSS feed

01 - Creating a simple Tile Engine

These tutorials will guide you through the basics of interacting with a Canvas element in reference to tile engines as well as slowly diving deeper into JavaScript techniques.
Some basic programming understanding is expected however there is nothing that can't be Googled.

The aim is to give an overview understanding of how tile engines are acheieved, leading into the use of JsIso and the simplicty of avaialble methods.

Using the HTML5 Canvas element to display some simple flat tiles is fairly straight forward.

In this sample we make use of a two dimensional array for our map representation and fillRect to draw our tiles rather than using graphics.
We don't care about scope or other cool things just now, let's just have the simple map displayed.

// Our init function contains all our code and will be called via the onLoad attribute in the <body> tag of our HTML page.
function init() {
    
    // The two dimensional map array as it sounds is basically your world and what will be drawn.
    // Each number can represet a different graphic or possible enviroment interaction.
    // In this tutorial case we only have two possible tiles, zero which is blank and one which is filled.
    var map = [
      [1,0,1,0,1],
      [1,1,1,0,1],
      [1,0,1,0,1]
    ];
    
    // The next part grabs the canvas element id of 'main' within our page <body>.
    var ctx = document.getElementById('main').getContext('2d');
    
    // Using two for loops we run through each of the array rows stored and their element values.
    for (var i = 0; i < map.length; i++) {
        for (var j = 0; j < map[i].length; j++) {
    
            // Check if the value is a 1, represeting a graphic should be drawn.
            if (map[i][j] === 1) {
                // Draw a rectangle at i & j position * 20 pixels so that
                // our 20x20 pixel squares are correctly positioned.
                ctx.fillStyle = '#FF0000';
                ctx.fillRect(j * 20, i * 20, 20, 20);
            }
    
        }
    }

}

Tutorial Outcome (View & Run Source)

1 comment

  1. First comment test!

    Iain Hamilton Sun, 26 Oct 2014

Please insert the result of the arithmetical operation from the following image:

Please insert the result of the arithmetical operation from this image. =