Skip to content Skip to sidebar Skip to footer

Javascript Load Images In Canvas With JCanvaScript

I am using JcanvaScript library to work with Html5 canvas and now I want to load some images in my Canvas, but only last image loading is successful, I can't see any other images b

Solution 1:

The bug has been identified in comment by MrOBrian : when the onload callbacks are called, i has the value it has at the end of the loop. That's the reason why you think that only last image loading is successful.

A standard solution is to embbed the content of the loop in a closure keeping the value of i :

for (i = 0; i < imagesUrl.length; i++){
     (function(i){
              var xImage = new Image();
              xImage.src = imagesUrl[i];
              xImage.onload = function(){
                  jc.start(canvas, fps);
                  jc.image(xImage, i*10, 0, 200, 200)
                          .id(imagesIdPrefix.toString() + i.toString());
                  jc.start(canvas, fps);
              }
              imagesObj.push(xImage);
       })(i);
   }

EDIT :

when you want to ensure all the needed images are loaded before running some code, you may use this function :

function onLoadAll(images, callback) {
    var n=0;
    for (var i=images.length; i-->0;) {
        if (images[i].width==0) {
            n++;
            images[i].onload=function(){
                if (--n==0) callback();
            };
        }
    }
    if (n==0) callback();
}

The images must have been provided their src first. You call the function like this :

onLoadAll(imagesObj, function(){
     // do something with imagesObj
});

Solution 2:

You need to make sure the images are loaded before you go and loop through them.

By defining your onload function inside of the for loop, the image may not have loaded by that point, and so the script will skip over it. And when it's done looping, the last image may be the only one that's loaded in time.

I would recommend adding a loader for each of the images outside the for loop, and when all the images are loaded go ahead and loop through the array.

A loader and checker looks something like this:

var loadedImages = [];
var loadedNumber = 3 //the number of images you need loaded    
var imageToBeLoaded = new Image();
imageToBeLoaded.onload = function() {
    loadedImages.push(true);
    checkImages();
}
function checkImages() {
    if (loadedImages.length != loadedNumber) {
        setTimeout(checkImages(),1000);
    } else {
        init(); //your draw function
    }
}

Post a Comment for "Javascript Load Images In Canvas With JCanvaScript"