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';
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';