Sunday, June 30, 2013

Drawing a tilemap example

Below is html5 sourcecode on how to draw a tilemap to the canvas. In the code a 2 dimensional array is used to store a map that is drawn to the screen every 16 milliseconds.


<!DOCTYPE=html>
<html><body>
<canvas id="myCanvas" width="320" height="240" style="border:1px solid #d3d3d3;">
Use different browser.
</canvas>
<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    var map = [
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,1],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],
        [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
    ]
    gameloop=setInterval(doGameLoop,16);
    function doGameLoop(){
        ctx.clearRect(0,0,c.width,c.height);
        for(var y = 0; y < map.length; ++y) {
            for(var x = 0; x < map[y].length; ++x) {
            if(map[y][x]==1) ctx.fillRect(x*16,y*16,16,16);
            }
        }
        ctx.fillText("Drawing a tilemap example.",10,10);
    }
    </script></body></html>