Champer Wu
Champer Wu

Reputation: 1271

image.onload return is not my wanted

I used the canvas tag to crop my image.

as following my code:

autoCropImage(url){
    var img = new Image();
    const cropApp = this;

let x = img.onload = function(){
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    const center_X = img.width/2, center_Y = img.height/2;
    let init_X=0, init_Y=0;
    ctx.drawImage(img, init_X, init_Y, img.width, img.height, 0, 0, img.width, img.height);

let dataUrl = canvas.toDataURL("image/jpeg", 1.0);
let dataUrl_short = dataUrl.replace("data:image/jpeg;base64,", "");
return dataUrl;
}();



img.src=url;
console.log(x);
return x;

}
//log result:
//data:,

I consider the log result should be a string of base64, but the callback is data:,

What's the problem in my code?

Upvotes: 0

Views: 61

Answers (2)

pixelscript
pixelscript

Reputation: 392

Are you wanting to return the data url without the data:image/jpeg;base64 part?

If so you're returning dataUrl instead of dataUrl_short in the method.

Upvotes: 0

Quentin
Quentin

Reputation: 943193

Your function is an IIFE. You are calling it immediately and then assigning its return value to img.onload.

(Then you assign the value of img.onload to x).

This means that you are not assigning a function to img.onload, so nothing happens after the image loads.

It also means that the image hasn't loaded when you try to pass it as an argument to ctx.drawImage.

Since the image hasn't loaded, there is no data to convert to a data URL with canvas.toDataURL.


You need to:

  1. Remove the () from after the function definition so it gets assigned to img.onload and called when the image loads
  2. Get rid of let x = because that will just be a copy of the function
  3. Read How do I return the response from an asynchronous call?

Upvotes: 1

Related Questions