Reputation: 5
I want draw a line of images with one onload function. I've tried this code
for(i = 0; i < 8; i++){
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "thumb.png";
imageObj.setAtX = i * 10;
imageObj.setAtY = i * 10;
imageObj.onload = function() {
context.drawImage(this, this.setAtX, this.setAtY);
};
}
(in java-script)
Upvotes: 0
Views: 1030
Reputation: 749
var imageObj = [];
for(var i=0;i<images.length;i++){
iy = parseInt(i/6) * 200;
ix = parseInt(i%6) * 200;
imageObj[i] = new Image();
imageObj[i].src = images[i];
// to set additinal parameter
imageObj[i].ix = JSON.parse(JSON.stringify(ix));
imageObj[i].iy = JSON.parse(JSON.stringify(iy));
// console.log(imageObj);
imageObj[i].onload = function() {
console.log(this.ix);
console.log(this.iy);
ctx.drawImage(this, this.ix, this.iy, 200, 200);
};
}
Upvotes: 0
Reputation:
Just reuse the image, and when the image has loaded then draw it in a loop - reorganize like this:
var canvas = document.getElementById('ctx');
var context = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload = function() {
for(var i = 0; i < 8; i++) context.drawImage(this, i * 10, i * 10);
// .. call next step from here
};
imageObj.src = "thumb.png";
Try to avoid setting new properties on native objects. In this case you don't need it, just iterate when the image has loaded.
Upvotes: 0
Reputation: 105035
// put the paths to your images in imageURLs[]
var imageURLs=[];
imageURLs.push("image1.png");
imageURLs.push("image2.png");
// the loaded images will be placed in imgs[]
var imgs=[];
var imagesOK=0;
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[]
}
Upvotes: 1