I've read about various kinds of ways getting image dimensions once an image has fully loaded, but would it be possible to get the dimensions of any image once it just started to load?
I haven't found much about this by searching (which makes me believe it's not possible), but the fact that a browser (in my case Firefox) shows the dimensions of any image I open up in a new tab right in the title after it just started loading the image gives me hope that there actually is a way and I just missed the right keywords to find it.
Answer: Use the HTML5 naturalWidth and naturalHeight You can easily find the original or intrinsic width and heigh of an image using the HTML5 image naturalWidth and naturalHeight properties. These properties are supported in all major web browsers such as Chrome, Firefox, Safari, Opera, Internet Explorer 9 and above.
To determine whether an image has been completely loaded, you can use the HTMLImageElement interface's complete attribute. It returns true if the image has completely loaded and false otherwise. We can use this with naturalWidth or naturalHeight properties, which would return 0 when the image failed to load.
Answer: Use the JavaScript clientWidth property You can simply use the JavaScript clientWidth property to get the current width and height of an image. This property will round the value to an integer.
In plain JavaScript, you can directly modify the CSS width and height property of the image. The following example demonstrates this by altering the CSS width property by specifying the absolute value in pixels and leave the browser to calculate the corresponding height while maintaining the aspect ratio.
You are right that one can get image dimensions before it's fully loaded.
Here's a solution (demo):
var img = document.createElement('img'); img.src = 'some-image.jpg'; var poll = setInterval(function () { if (img.naturalWidth) { clearInterval(poll); console.log(img.naturalWidth, img.naturalHeight); } }, 10); img.onload = function () { console.log('Fully loaded'); }
The following code returns width/height as soon as it's available. For testing change abc123
in image source to any random string to prevent caching.
There is a JSFiddle Demo as well.
<div id="info"></div> <img id="image" src="https://upload.wikimedia.org/wikipedia/commons/d/da/Island_Archway,_Great_Ocean_Rd,_Victoria,_Australia_-_Nov_08.jpg?abc123"> <script> getImageSize($('#image'), function(width, height) { $('#info').text(width + ',' + height); }); function getImageSize(img, callback) { var $img = $(img); var wait = setInterval(function() { var w = $img[0].naturalWidth, h = $img[0].naturalHeight; if (w && h) { clearInterval(wait); callback.apply(this, [w, h]); } }, 30); } </script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With