greyBow
greyBow

Reputation: 1348

Bitmap image not showing up in canvas

I need some direction here as I'm not clear on what I'm doing wrong. All I'm trying to do is a load a bitmap in the center of the canvas but it's not showing up. My file path is correct and I don't see what I might have coded incorrectly, where am I going wrong?

var canvas, stage, centerX, centerY;

function init() {
    'use strict';

    canvas = document.getElementById("easel");
    stage = new createjs.Stage(canvas);
    centerX = canvas.width / 2;
    centerY = canvas.height / 2;

    var ship = new createjs.Bitmap("../images/millenium.png"),
        shipCenterX = ship.width / 2,
        shipCenterY = ship.height / 2;

    ship.x = centerX;
    ship.y = centerY;
    ship.regX = shipCenterX;
    ship.regY = shipCenterY;

    stage.addChild(ship);
    stage.update();
}

Upvotes: 0

Views: 271

Answers (2)

bazeblackwood
bazeblackwood

Reputation: 1204

The way this library appears to handle drawing to the canvas is by calling stage.update() which they recommend attaching to their "tick" event (e.g. http://www.createjs.com/docs/easeljs/classes/Stage.html)

Basically, we need to keep continually redrawing the canvas, and createjs gives us a method to do that, like so:

createjs.Ticker.addEventListener("tick", handleTick);
function handleTick(event) {
     stage.update();
}

However, since you haven't made your stage globally accessible, I tweaked your init function slightly so that we can access stage by returning it at the end of the function. Thus you can set stage in the global scope to the result of the function:

var stage = init();

And handleTick will use that stage by default. However if you're thinking of reusing your objects outside of your init() function, you may want to consider passing them to the init function or keeping their initial data structure outside of the init function to make them easier to access.

https://jsfiddle.net/jpgw1oka/

Upvotes: 1

Berni
Berni

Reputation: 151

And make sure you are loading the CreateJS library: https://code.createjs.com/createjs-2015.11.26.min.js.

Remove the 'use strict'.

And make sure you are declaring your variables and function calls inside a window.onload event listener.

E.g.

var canvas, stage;

function init() {

canvas = document.getElementById("easel");
stage = new createjs.Stage(canvas);

var ship = new createjs.Bitmap("../images/millenium.png");

ship.x = Math.floor(stage.canvas.width * 0.5);
ship.y = Math.florr(stage.canvas.height * 0.5);
ship.regX = Math.floor(ship.image.width * 0.5);
ship.regY = Math.floor(ship.image.height * 0.5);

stage.addChild(ship);
stage.update();

}

Upvotes: 0

Related Questions