Get image width and height not working in Javascript - zero value

What is the correct way of getting image width and height in Javascript ? I have tried to use the following code, but I get 0 value on the first attempt. I get the correct value only when calling the function again.

var i = new Image();
var width = i.width;
var height = i.height;
i.src = 'https://www.myweb.com/image.png';
13 Jun 2022 at 06:55 PM
0give a positive ratinggive a negative ratingshow more
LarsLars
Hi,

You are getting zero value on the first attempt, because image is not fully loaded at the moment when you try to measure its width and height. To make the feature work well, you have to add an onload function into it:


var i = new Image();
i.onload = function(){
var width = i.width;
var height = i.height;
alert('Width: '+width+' / Height: '+height);
}
i.src = 'https://www.myweb.com/image.png';

14 Jun 2022 at 11:25 AM
0give a positive ratinggive a negative ratingshow more
TimTim
Share on FacebookShare on TwitterShare on LinkedInSend email
Follow us on Facebook
2022 AnswerTabsTermsContact us