var icon1 = new Image();
var wid1;
var hei1;
icon1.onload = function () {
wid1 = icon1.width;
hei1 = icon1.height;
};
icon1.src = resource;
var rati = wid1 / hei1;
What I am trying to do is to get the width and height of the image and then calculate the ratio that will further help to maintain the aspect ratio of the image.
But when I run this code, lot of times I get the width and height of image as 0 that will result turning ratio to NaN and finally the image never loads because of 0 height and width. Any Help?
I had a problem where the image.width and image.height were 0 within the onload callback. They were set for jpg files and not set when I loaded a png.
I fixed this by using this.width and this.height in the onload callback function. Those were not zero.
Maybe this will help someone else. I was using chrome.
This operation runs asynchronously. The line:
var rati=wid1/hei1;
Runs regardless if the image is loaded or not. This means the wid1 and hei1 are undefined and dividing two undefined values results to NaN.
Make sure wid1 and hei1 are loaded before doing operations on them. What you can do is place the divide operation inside the onload handler (as well as everything else that depends on those values:
var icon1, wid1, hei1, rati;
//create our image object
icon1 = new Image();
icon1.onload = function () {
wid1 = icon1.width;
hei1 = icon1.height;
rati = wid1 / hei1;
//everything else that depends on these variables
//should be placed here as well
};
//start loadin'
icon1.src = resource;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With