Reputation: 1106
Help me please to understand where I should Image.onload to drawImage correctly?
My situation:
I'm loading my images from Json file and store them in array (imgArray it's the array with pictures links):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'img/img.json', false);
xhr.send();
imgArray = JSON.parse(xhr.response);
Than I create a function that accept my imgArray and makes new Images for every link and put them into new array:
function loadImage(ImgArray){
var pics = [];
var img;
ImgArray.forEach(function(link){
img = new Image();
img.src = link;
pics.push(img.src);
});
return pics;
};
And for example I want to draw one of those images:
function draw(){
ctx.drawImage(loadImage(imgArray)[0]),0,0,100,100);
};
The result of draw() function is the array with the new Image links, but I can't draw them because of, as I know, that they aren't loaded yet. Please someone tell me when I should do this?
Here is the link to the full story: http://jsfiddle.net/L23oam57/1/
Upvotes: 0
Views: 39
Reputation: 722
Recrusive call:
var counter = 0;
var pics = [];
function loadImage(img){
var img;
img = new Image();
img.src = link;
img.onload = function(e){draw(img)};
pics.push(img.src);
};
function draw(image){
ctx.drawImage(image),0,0,100,100);
if(counter != imageArray.length)
{
loadImage(ImgArray[counter]);
counter++;
}
};
Upvotes: 2