Categories
JavaScript Answers

How to determine original size of image cross browser with JavaScript?

Spread the love

Sometimes, we want to determine original size of image cross browser with JavaScript.

In this article, we’ll look at how to determine original size of image cross browser with JavaScript.

How to determine original size of image cross browser with JavaScript?

To determine original size of image cross browser with JavaScript, we get the dimensions from the image element’s onload callback.

For instance, we write

const newImg = new Image();

newImg.onload = () => {
  const { height, width } = newImg;
  console.log(width, height);
};

newImg.src = imgSrc;

to create an img element with the Image constructor.

Then we set its onload property to a function that gets the width and height of the image.

We then set the src property of the image to imgSrc which will trigger onload to run.

Conclusion

To determine original size of image cross browser with JavaScript, we get the dimensions from the image element’s onload callback.

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 *