dmarcos89
dmarcos89

Reputation: 59

Drawing array of images on CANVAS

I´m trying to draw an array of images on a canvas, but i have a problem with the onload method.

I think it could be a problem because the images cannot be drawn on the canvas before the onload is completed, and because its inside a FOR probably i lost every reference...

Here is my code:

// Grab the Canvas and Drawing Context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

// Create an image element
var bg = document.createElement('IMG');


// When the image is loaded, draw it
img.onload = function () {
    ctx.drawImage(bg, 0, 0);

}

// Specify the src to load the image
fondo.src = "../img/auxfinal.png";
img.src = "../img/bolso.png";


// var res is is my array where i have on each position (img name, x, y)

var arrayLength = res.length;

for (var i = 0; i < arrayLength; i++) {
    var aux = document.createElement('IMG');

    aux.onload = function () {
        ctx.drawImage(aux, res2[1].substr(0,res2[1].length-2), res2[2].substr(0,res2[2].length-2));
    }




}

Upvotes: 0

Views: 2548

Answers (1)

markE
markE

Reputation: 105035

As @gtramontina says, your aux loading loop won't work because it's not setting any .src and also because the first aux variable will be killed by the second pass through the loop (etc).

You might want to add an image loader to your toolkit...Here's one (but there are many out there):

// image loader

var imagesOK=0;
var imgs=[];

var imageURLs=[];  
// put the paths to your images here
imageURLs.push("../img/auxfinal.png");
imageURLs.push("../img/bolso.png");
// ... and push all your other images also

loadAllImages(start);

function loadAllImages(callback){
    for (var i=0; i<imageURLs.length; i++) {
        var img = new Image();
        imgs.push(img);
        img.onload = function(){ 
            imagesOK++; 
            if (imagesOK>=imageURLs.length ) {
                callback();
            }
        };
        img.onerror=function(){alert("image load failed");} 
        img.crossOrigin="anonymous";
        img.src = imageURLs[i];
    }      
}

function start(){

    // the imgs[] array now holds fully loaded images

    // the imgs[] are in the same order as imageURLs[]

    // for example,
    // auxfinal.png is in imgs[0] & this will draw auxfinal.png
    ctx.drawImage(imgs[0],0,0);

}

Upvotes: 2

Related Questions