Search code examples
javascripthtmlcsscanvaskineticjs

KineticJS images not working locally, sometimes work online


I'm testing KineticJS right now. I tried adding an image to the canvas following this tutorial. I changed a bit the code but it's relatively the same.

What's confusing is that locally it's not working at all...no images are displayed and no errors at all. Online is a different story, images are loaded BUT sometimes it looks like the images are not loading.

This is what I have: http://codepen.io/semajtwin/pen/nIafc

I thought maybe it was the browser as well, I tried on three different browsers (Chrome, Firefox and Internet explorer) but still ended up with the same result.

I just can't figure out what's wrong really.

Thanks in advance for any help.


Solution

  • @RobinvdA is correct that you need to give the images time to load.

    Your draw draw_img(); and draw_img2(); are being called before the images are fully loaded.

    The fix is to put the draw_img code inside onload, like this:

    Here's some refactored code and a Demo: http://jsfiddle.net/m1erickson/fLPZt/

    // declare sun_img outside `onload` so it's accessible later
    
    var sun_img;
    
    // create a Kinetic.Image of the sun
    
    var sunReady = false;
    var sunImage = new Image();
    sunImage.onload = function () {
        sun_img = new Kinetic.Image({
            x: 0,
            y: 0,
            width: 200,
            height: 200,
            image: sunImage,
            draggable: true
        });
        layer.add(sun_img);
        layer.draw();
    };
    sunImage.src = "http://2.bp.blogspot.com/-GDMbp9j3iSo/Tgh24-ighVI/AAAAAAAAAgE/a4glfYd5-68/s200/radiantsunheliumballoon.jpg";