Search code examples
javascripthtml5-canvaseaseljscreatejs

createjs.Bitmap() image not being displayed


I've been really stuck on this simple problem. I've search around and have found "solved" solutions but can't seem to get them to work on my end. I'm trying to load a button image as a createjs.Bitmap() object onto my stage/canvas. I'm doing it exactly as it appears in the documentation and tutorials and can't seem to get the image to actually appear on my canvas. Here's the game.js file associated with this:

// GLOBAL VARIABLES
var gameCanvas;             // The canvas the game will be contained within
var gameStage;              // The primary stage holding all of our game elements
var mainMenuContainer;      // The container for the main menu elements

// INITIALIZATION METHODS
// init() - sets up the game gameStage and game elements. This gets called by the <body> onLoad() event
function init() {
    // initialize gameStage to manage all of the game elements
    gameStage = new createjs.Stage("gameCanvas");

    // add a ticker to the gameStage object
    createjs.Ticker.on("tick", gameStage);

    // initialize the main menu for our game
    initMainMenu();

    // update the stage
    gameStage.update();
}

// initMainMenu() - sets up the mainMenuContainer element and attaches all of the main menu game elements to the
// container. This is called from the main init() function when the main menu is ready to be initialized
function initMainMenu() {
    // initialize the container to manage all of the elements to be displayed on the main menu
    mainMenuContainer = new createjs.Container();

    var mainMenuStartBitmap = new createjs.Bitmap("../static/img/gui/mainMenuStartButton.jpg");

    // add all elements of the main menu to the mainMenuContainer
    mainMenuContainer.addChild(
        mainMenuStartBitmap
    );

    // add the mainMenuContainer to the gameStage
    gameStage.addChild(mainMenuContainer);

    // update the stage
    gameStage.update();
}

Does anyone see anything wrong with the way I'm creating the bitmap and adding the children to the stage/container?


Solution

  • The image is not loaded yet when you update your stage.

    You should either:

    • Continually update the stage. The image will be displayed once it loads
    • Listen for the image.bitmap.onload event, and update your stage again at that point
    • Properly preload your images before you draw and update your stage.. You can use PreloadJS to do that. http://preloadjs.com

    Cheers.