2

First time poster here but definitely not a first time reader.

My question is aimed directly at this portion of code I have. I am currently learning how HTML 5 canvases work and am designing my own RPG style game for a University project. After looking around I found some good tutorials on this guys blog, I have followed his code and triple checked it but images are now showing up.

I tried putting an alert() before and after when the image is called to the canvas under drawMap(). It works before the image is drawn but not after, leading me to believe it is something to do with my image rendering. Can someone double check my code and see what is going on? It's driving me insane!

<canvas id="game-viewport" width="760" height="440"></canvas>

<script>

    window.onload = init;

    var map = Array([0,0],[0,0],[0,0],[0,0]);
    var tileSize = 40;

    tileTypes = Array("grass.png");
    tileImage = new Array();

    var loaded = 0;
    var loadTimer;

    function loadImage(){
        for(i = 0; i < tileTypes.length; i++){
            tileImage[i] = new Image();
            tileImage[i].src = "./game/lib/icons/own_icons/" + tileTypes[i];
            tileImage[i].onload = function(){
                loaded++;
            }
        }
    }

    function loadAll(){
        if(loaded == tileTypes.length){
            clearInterval(loadTimer);
            drawMap();
        }
    }

    function drawMap(){
        var mapX = 80;
        var mapY = 10;

        for(i = 0; i < map.length; i++){
            for(j = 0; j < map[i].length; j++){
                var drawTile = map[i][j];
                var xPos = (i - j) * tileSize;
                var yPos = (i + j) * tileSize;
                ctx.drawImage(tileImage[drawTile], xPos, yPos);
            }
        }
    }

    function init(){
        var canvas = document.getElementById('game-viewport')
        var ctx = canvas.getContext('2d');
        loadImage();
        loadTimer = setInterval(loadAll, 100);
    }

</script>
Brad Bird
  • 737
  • 1
  • 11
  • 30

1 Answers1

3

The only problem is that ctx is not defined in your drawMap function.

Either pass ctx in to the function as an argument or make it a global variable.

I was lazy and did the second, but you should really do the first. Working code:

http://jsfiddle.net/YUddC/


You really should have the Chrome debugger (or whatever browser you use) on 100% of the time you're developing.. If you did, you'd see an error saying that ctx is not defined in drawMap. If you're using Chrome and press F12 to open developer tools and go to the scripts tab, you'd see this:

enter image description here

Which makes the problem pretty clear!

Simon Sarris
  • 62,212
  • 13
  • 141
  • 171
  • Yeah that makes sense! The tutorial I was looking at doesn't do that and it somehow works? Thanks for the heads up however. – Brad Bird Feb 13 '12 at 10:08