Categories
JavaScript Answers

How to Determine Image Dimensions in JavaScript?

Spread the love

To determine image dimensions in JavaScript, we can use the Image constructor to create the image object and get the dimensions from there.

For instance, we write:

const img = new Image();
img.src = "https://i.picsum.photos/id/686/200/300.jpg?hmac=KpugvfnM7VFRRbf_yihA6yObvfaWEJEEXeeFEqmVegQ";
img.onload = () => {
  const actualwidth = img.width;
  const actualheight = img.height;
  console.log(actualwidth, actualheight)
}

to create the Image instance and assign it to img .

Next, we set the src property of the image.

Then we set the img.onload property to a function.

In the function, we get the width and height properties of img , which are the width and height of the image respectively.

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 *