thebiglebowski11
thebiglebowski11

Reputation: 1461

image load on end event

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]);

Upvotes: 1

Views: 6366

Answers (1)

markE
markE

Reputation: 105035

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();
}

Upvotes: 2

Related Questions