Sometimes, we want to get width height of remote image from URL with JavaScript.
In this article, we’ll look at how to get width height of remote image from URL with JavaScript.
How to get width height of remote image from URL with JavaScript?
To get width height of remote image from URL with JavaScript, we can use the naturalWidth and naturalHeight properties.
For instance, we write
const img = new Image();
img.addEventListener("load", () => {
console.log(img.naturalWidth, img.naturalHeight);
});
img.src = url;
to create an img element with the Image constructor.
Then we add an event listener for the load event with addEventListener.
In it, we get the width and height of the image with naturalWidth and naturalHeight.
Then we set img.src to url to load the image and run the load event handler.
Conclusion
To get width height of remote image from URL with JavaScript, we can use the naturalWidth and naturalHeight properties.