HomeTutorsContact

How to find height and width of base64 image loaded asynchronously?

By Gulshan Saini
Published in JavaScript
July 23, 2020
1 min read

Getting the height and width of an image whose src is known before DOM is constructed is straightforward; we can select the image using JavaScript and get the width and height attributes directly. However, if you try to get the dimensions of an image(normal or base64) that is dynamically loaded, you might get 0x0 value in return for width and height respectively.

I have prepared below example to demonstrate this

Example of loading images dynamically
Example of loading images dynamically

In the above example:

  • Flowerpot and Cosco ball image source is already known before the DOM is constructed
  • Volleyball and football images are added to the DOM dynamically
  • Flowerpot and Cosco ball images are normal image URLs
  • Volleyball and football images are base64 images

As we can see in console messages, the browser returned the width and height of the images whose source was already known however for the dynamically loaded images, it returned 0x0 as image dimension. Browser returns 0x0 value as the image is yet to be loaded.

To correctly calculate the dimensions of dynamically loaded image we should use the image onload event which, will ensure the height gets calculated only after image is loaded.

Once we fix the issue, the browser will correctly communicate the dimension of the image back to us, as we can see in the screenshot below.

get image size after load event
get image size after load event

Output


Tags

#javascript
Previous Article
How to load any npm module in browser?

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to convert Set to Array in JavaScript?

October 28, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media