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';
0
give a positive ratinggive a negative rating
13 Jun 2022 at 06:55 PM
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';

0
give a positive ratinggive a negative rating
14 Jun 2022 at 11:25 AM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us