• Post category:JavaScript
  • Reading time:2 mins read

To get the current size (width and height) of an image using JavaScript, you can use the naturalWidth and naturalHeight properties of the Image object.

Here is an example code snippet:

const img = new Image();
img.src = 'https://example.com/image.jpg';
img.onload = () => {
  const width = img.naturalWidth;
  const height = img.naturalHeight;
  console.log(`Image size: ${width}x${height}`);
};

In this example, we create a new Image object and set its src attribute to the URL of the image we want to get the size of. We then attach an onload event listener to the img object, which will be called once the image has finished loading. Inside the event listener, we can access the naturalWidth and naturalHeight properties to get the size of the image.

Note that the onload event listener is important because the image may not be loaded immediately when you create the Image object. If you try to access the naturalWidth and naturalHeight properties before the image is loaded, you may get incorrect values or an error.

That’s it for today.
Thank you for reading. Happy Coding..!!

Leave a Reply