Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  184] [ 3]  / answers: 1 / hits: 5373  / 10 Years ago, tue, june 10, 2014, 12:00:00

i am resizing an image using canvas and javascript... After the image has finished, I want to do some logic. Is there an event for finished? I tried onloadend but it never gets called:



var fr = new FileReader();
fr.onload = function (e) {
var img = new Image();

img.onloadend = function() {
console.log('finished logic here');
}
img.onload = function(){
var MAXWidthHeight = 488;
var ratio = MAXWidthHeight / Math.max(this.width,this.height);
var w = this.width * ratio;
var h = this.height * ratio;
var c = document.createElement(canvas);
c.width = w;
c.height = h;
c.getContext(2d).drawImage(this,0,0,w,h);
this.src = c.toDataURL();
document.body.appendChild(this);
}
img.src = e.target.result;
}
fr.readAsDataURL(files[i]);

More From » canvas

 Answers
4

An image is loaded asynchronously, but...



All processing inside .onload is synchronous, so you could just add a callback like this:



img.onload = function(){
var MAXWidthHeight = 488;
var ratio = MAXWidthHeight / Math.max(this.width,this.height);
var w = this.width * ratio;
var h = this.height * ratio;
var c = document.createElement(canvas);
c.width = w;
c.height = h;
c.getContext(2d).drawImage(this,0,0,w,h);
this.src = c.toDataURL();
document.body.appendChild(this);

// after this img has been appended, execute myCallback()
myCallback();
}

function myCallback(){
console.log(I'm called after this img has been appended);
}


If you load multiple images, you will have multiple .onloads and therefore you will have myCallback executed multiple times. If you just want myCallback executed once after all images have been appended, you would set a countdown variable that delays calling myCallback until all images have been appended.



var countdown=imageCount;  // imageCount is the total count of images to be processed

// and then in .onload

if(--countdown==0){
myCallback();
}

[#44665] Monday, June 9, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
makaylahh

Total Points: 128
Total Questions: 106
Total Answers: 97

Location: Tanzania
Member since Wed, Feb 24, 2021
3 Years ago
;