2

I saw similar post about my problem but they only display width and height. But I have to return these variables to use them later.

here is my code, I get always "0" ;

var img = new Image();
img.src = "my_image.jpg";
newWidth = 0;
wnewHeight = 0;
img.onload = function() {
newWidth = (img.width*0.5);
newHeight = (img.height*0.5);
//return [newWidth , newHeight];
}

alert (newWidth);

2 Answers2

0

Use this instead of img.

Also, you need to put the alert inside the callback function as the image is loaded asynchronously. So

 var img = new Image();
    img.src = "my_image.jpg";
    newWidth = 0;
    wnewHeight = 0;
    img.onload = function() {
    newWidth = (this.width*0.5);
    newHeight = (this.height*0.5);

    alert (newWidth);

    return [newWidth , newHeight];
    }
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
  • @bourax, there was a mistake in my answer, try it now – AmmarCSE May 13 '15 at 15:23
  • I tried this before and it works fine, this is what I told.But, I don't want to display, I want to be able to use them later (out of the function) –  May 13 '15 at 15:28
  • You can return empty object and then in load add height and width properties. Or use callback. – jcubic May 13 '15 at 15:30
  • @bourax "*I want to be able to use them later (out of the function)*" -- Have your `onload` function call another function. Or have `onload` set a boolean flag (like `hasLoaded`) that indicates whether the images has loaded yet. – apsillers May 13 '15 at 15:36
0

Here is how I fixed it. I handled the onload return in a variable X:

var img = new Image();
img.src = "my_image.jpg";
newWidth = 0;
wnewHeight = 0;
var x = img.onload = function() {
newWidth = (this.width*0.5);
newHeight = (this.height*0.5);
return [newWidth , newHeight];
}();
alert (x[0]); //for the weight
alert (x[1]); //for the height
  • This only works when the image loads immediately and no `onload` is needed. That only happens when the image has been loaded previously and is already in the browser's cache. You are not even setting `img.onload` to a function; you are setting it to an array. Try out your code with an image you haven't loaded recently (or do a hard refresh with Ctrl+Shift+R) and you'll see that it does not work for initial loads. For example, check out this fiddle: http://jsfiddle.net/5LzacLz7/ – apsillers May 13 '15 at 16:11
  • owww that's true ?? so how do I fix it ?? –  May 18 '15 at 09:05