Get the real width and height of an image with JavaScript? (in Safari/Chrome)
Utilize an Image
object and its onload
event to fetch the intrinsic naturalWidth
and naturalHeight
, thereby revealing the image's actual dimensions in Chrome and Safari.
The dredged details
When dealing with images on the web, especially those dynamically loaded or part of complex layouts, things can get a bit… tricky. CSS can stretch or squeeze the poor thing to oblivion, while your script innocently believes it to be of a different size. How's that for a plot twist?
Unwrapping naturalWidth and naturalHeight
Enter naturalWidth
and naturalHeight
, the superheroes in our tale. 🦸♀️🦸♂️ These properties bombard your image with their charm and charisma, making it reveal its true size, untouched by the treacherous CSS. Don't judge an image by its display size!
The enigma of fully loaded images
Before you summon our superheroes, make sure their nemesis, the image, is fully loaded. You can do this with the help of .onload
event, a little secret that waits for the image to buckle up before the show begins.
Mastering the cross-browser game
While naturalWidth
and naturalHeight
are widely supported, it's best to double-check on caniuse.com. Because, as we know, not all heroes wear capes, just like not all browsers support all properties.
Error handling: Necessary evil
In the off-event that the image fails to load, utilize the .onerror
event. Saving your users' day with an alternate image or message would make you the unsung hero of your application.
jQuery: A twist in the tale
If you’re using jQuery, you can encapsulate the logic in a custom jQuery function. Because a little dash of consistency never hurt anyone.
Riding the HTML5 wave
HTML5 has significantly smoothed the road when dealing with embedded content like SVGs. These properties can also measure SVG graphics inside image tags, creating a uniform method to handle various content types.
Was this article helpful?