How to Get Image Dimensions (Width & Height) with Javascript

javascript
Published on February 12, 2018

Dimensions of an image can be retrieved in Javascript by :

  • Using naturalWidth and naturalHeight properties — this would give the actual dimensions of the image.
  • Using width and height properties — this would give the dimensions of the image as rendered in the page.

However it is important to consider two situations before directly finding the dimensions of the image :

  • The image may not have been fetched, and trying to get the dimensions in such cases will give incorrect results. We need to make sure that image is loaded first.
  • We also need to check whether image is loading from the browser's cache.
// image is already loaded
if(document.querySelector("#img-element").complete) {
	var image_width_actual = document.querySelector("#img-element").naturalWidth;
	var image_height_actual = document.querySelector("#img-element").naturalHeight;

	var image_width_rendered = document.querySelector("#img-element").width;
	var image_height_rendered = document.querySelector("#img-element").height;
}
else {
	document.querySelector("#img-element").addEventListener('load', function() {
		var image_width_actual = this.naturalWidth;
		var image_height_actual = this.naturalHeight;

		var image_width_rendered = this.width;
		var image_height_rendered = this.height;
	});
}
  • The load event handler of the image element is fired when it has finished loading. However if image is loaded from cache, the load event handler may not be executed for some browsers.
  • The complete property of the image element returns true if the browser has finished fetching the image. This can be used to check whether image is already loaded in cache, so there is no need to apply the load event.
In this Tutorial