Categories
JavaScript Answers

How to get image dimensions with JavaScript?

Spread the love

Sometimes, we want to get image dimensions with JavaScript.

In this article, we’ll look at how to get image dimensions with JavaScript.

How to get image dimensions with JavaScript?

To get image dimensions with JavaScript, we can use the width and height properties.

For instance, we write

const img = new Image();

img.onload = () => {
  const height = img.height;
  const width = img.width;
  //...
};

img.src = url;

to create an img element with the Image constructor.

Then we get the height and width of the img image in the img.onload method, which runs when the image is loaded.

Then we load the image by setting img.src to the url of the image.

Conclusion

To get image dimensions with JavaScript, we can use the width and height properties.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *