问题
My goal is to create an array of imageData from a series of png images.
In order to do this I use a for loop to go through the images, put them in the canvas and then retrieve and store the created imageData in an array.
The problem is that the image does not have enough time to be loaded in the canvas. My solution for now is to have a timer leave enough time but it's horrible.
I can't seem to find any solution to this problem. Is there a way to have an "onload" function for the canvas?
for(var i=1;i<50;i++){
(function(i){
setTimeout(function(){
return function(){
var newpath = path+i+".png"; //path to the image
baliseimg.onload = function(){ //baliseimg : html image tag
ctxt.drawImage(baliseimg,0,0);
ctxt.fillText(i, 50, 50); //just to stamp the image number on the imagedata
imgs[i-1]=ctxt.getImageData(0,0,512,512);
}
baliseimg.src=newpath;
}();
},100*i); //100ms works, limit seems to be at 40
}(i));
}
Thank you for your time.
回答1:
No, according to http://www.w3schools.com/jsref/event_onload.asp
But you still can use img
elements' onload
in order to do canvas
manipulation. This article may help you.
Bonne chance !
回答2:
Here's code to preload all your images.
When they are fully loaded the start() function is called.
// image loader
var imageURLs=[];
var imagesOK=0;
var imgs=[];
// put the paths to your images in imageURLs[]
imageURLs.push("yourImage1.png");
imageURLs.push("yourImage2.png");
imageURLs.push("yourImage3.png");
imageURLs.push("yourImage4.png");
imageURLs.push("yourImage5.png");
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 holds fully loaded images
// the imgs[] are in the same order as imageURLs[]
// for example, draw the images on the canvas
var nextX=10;
for(var i=0;i<imgs.length;i++){
context.drawImage(imgs[i],nextX,10);
nextX+=imgs[i].width;
}
}
来源:https://stackoverflow.com/questions/23220385/is-there-an-onload-function-for-html-canvas