Search code examples
javascripthtmlcanvaseaseljsstage

Very basic EaseLJS issue. I can't get it to work


I'm very new to javascript and EaseLJS but I don't understand how this doesnt work. I have a html file:

   <!DOCTYPE html>
<html>
<head>

    <script src="easeljs-0.7.1.min.js"  type="text/javascript"></script>
 <script src="game.s.js"  type="text/javascript"></script>  
 <script>
 function init() {
        renderLevel();
    }
 </script>

</head>
<body onLoad="init();">
        <canvas id="canvas" width="500" height="300">
        alternate content
</canvas>
</body>
</html>

The game.s.js file looks like:

function renderLevel()
{

    var stage = new createjs.Stage("canvas");
    var bitmap = new createjs.Bitmap("brick.png");
    stage.addChild(bitmap);

    bitmap.x = 32;
    bitmap.y = 32; 
    stage.update();   
    alert(stage.canvas);
    alert(bitmap.name);

}

The alert I just put there to check the values. stage.canvas rightly points to the HTML5Canvas element but the image won't show!

What am I missing here? :)

Thank you


Solution

  • The problem is that you are adding the image to stage before it loads, then there's no image yet. You need to wait for the image to load before adding it to the stage.

    You can do this by using a preload(); function to load all the images before calling init(); or renderLevel();. Here's what this function should look like:

    function preload(images, callback) {
        var count = images.length;
        if (count === 0) {
            callback();
        }
        var loaded = 0;
        $(images).each(function () {
            $('<img>').attr('src', this).load(function () {
                loaded++;
                if (loaded === count) {
                    callback();
                }
            });
        });
    }
    

    ...and then you can use it like so:

    preload(["image1.png", "image2.png"], init());
    

    JSFiddle Demo