javascriptimagebitmapeaseljspreloadjs

CreateJS - Image bitmap doesn't alway show up


I suspect that the answer will lie in PreloadJs, however, I've removed my tinkering around with it in my code to simplify it. Here is the most important part:

let stage = new createjs.Stage('easel'),
bitmap = new createjs.Bitmap('http://www.skrenta.com/images/stackoverflow.jpg');
stage.addChild(bitmap);
stage.update();

So now the problem, this is what you get when you run my code after the first time:

original

Nothing wrong.

However, the first time you visit, the image isn't cached yet it, and doesn't show up. The same thing happens when you do hard reset the page(ctrl + r on windows). This is obviously a big deal because the first time you visit the page, it won't have images. Here is what I've tried:

So basically while some of these solutions while they work some of the time, some are hackish and all work only a percentage, or less of the time. What is the best solution?

One thing is that when I do something, such as resizing the page, the image would show up. I was not able to recreate this in my sample code. I believe this happened because when I initially ran stage.update it wasn't ready to show, so it didn't. Again simply running stage.update again a second later isn't good enough.

Note: I do not believe this to be a duplicate of this question as there are no answers, it is a year old, they were unable to give some details, and the only solution offered in the comments failed.


Solution

  • Your image is not loaded when you call stage.update. Even if you preload it, if you pass a string path to the Bitmap, it still takes time to initialize, but even if its just milliseconds, you have asked the stage to draw before it is ready.

    The solution is to draw once the image is complete, and ensure you use the image, instead of a string path.

    To fix your code:

    let stage = new createjs.Stage('easel'),
    bitmap = new createjs.Bitmap('http://www.skrenta.com/images/stackoverflow.jpg');
    stage.addChild(bitmap);
    bitmap.image.onload = function() {
        stage.update();
    }
    

    To fix your preload code:

    queue.on('complete', draw, this)
    queue.load(imageUrl)
    
    function draw() {
      let bitmap = new createjs.Bitmap(queue.getResult("imgId")); // Reference
      stage.addChild(bitmap);
      stage.update();
    }
    

    Here is a more complete answer: easeljs not showing bitmap