0

Using EaselJS, I'm attempting to add a bitmap to a canvas.

I have an Entity object that is defined as such:

const Entity = class {
    constructor(src, x, y) {
        let image = new Image();
        image.src = src;
        this.bitmap = new createjs.Bitmap(image);
        this.bitmap.x = x;
        this.bitmap.y = y;
    };

    get image() {
        return this.bitmap;
    }

    get position() {
        return this.bitmap.x + ', ' + this.bitmap.y;
    };

    handleMovement(event) {
        if (event.keyCode === 38) this.bitmap.y -= 2;
        if (event.keyCode === 40) this.bitmap.y += 2;
        if (event.keyCode === 37) this.bitmap.x -= 2;
        if (event.keyCode === 39) this.bitmap.x += 2;
    };
};

I use this to make an Entity object named "man" that I add to the EaselJS stage:

const stage = new createjs.Stage('cnv');
const man = new Entity('/img/man.png', 100, 40);
stage.addChild(man.image);
stage.update();              // first invocation
$(document).bind('keydown', function (event) {
    "use strict";
    stage.update();          // second invocation
});

As represented in the snippet above, I have two stage.update() calls.

My jQuery callback is only invoked once a key is pressed. It only contains

stage.update();

However, until I press a key, the entity bitmap does not appear on the canvas. This leads me to believe that stage.update() is only working within the scope of the callback function.

How can I change this so that the bitmap appears by updating the canvas without having to invoke a key press?

Orange Receptacle
  • 1,173
  • 3
  • 19
  • 40

1 Answers1

0

Instead of having my first stage.update() appear right after adding it to the stage, I had it put within a jQuery ready callback as such:

$(document).ready(function () {
    stage.update();
});

Now, when the page is loaded, it updates accordingly so that the bitmap shows up.

Orange Receptacle
  • 1,173
  • 3
  • 19
  • 40
  • This may not be enough. You have to wait until the bitmap is loaded, and since it is not included in the DOM, the `ready` function may fire before the bitmap is loaded. It is recommended to listen for the image to be loaded, and calling `stage.update()` again. https://stackoverflow.com/questions/20850634/easeljs-not-showing-bitmap/20860996#20860996 – Lanny Sep 17 '17 at 19:38