Understanding image dimensions is critical for web development. You often need to know the height and width of an image to properly layout a web page.
In this comprehensive guide, I‘ll explain three methods for getting image dimensions with JavaScript:
- Using the naturalWidth and naturalHeight properties
- Loading the image and fetching width/height
- Drawing the image on a canvas and fetching its width/height
I‘ll provide detailed code examples for each approach and explain the pros and cons. By the end, you‘ll have expert knowledge for getting image dimensions with JavaScript.
Why Image Dimensions Matter
Here are some examples where you need to know an image‘s dimensions:
- Reserving the appropriate space before an image loads
- Scaling an image proportionally
- Cropping or manipulating images client-side
- Creating thumbnail previews
- Building responsive layouts
Without the height and width, it‘s guesswork. You risk overlapped or distorted images that create a poor user experience.
Fetching dimensions also avoids another common mistake – hard coding image sizes. It keeps your code DRY and adaptable.
So let‘s dive in and uncover the techniques!
Method 1: naturalWidth and naturalHeight
All image elements have naturalWidth and naturalHeight properties. These return the true pixel width and height when loaded:
const img = document.getElementById(‘my-img‘);
const width = img.naturalWidth;
const height = img.naturalHeight;
This approach requires no extra work. It fetches the actual rendered dimensions automatically.
Pros:
- Simple and straight-forward
- Leverages built-in browser properties
- Returns the true rendered dimensions
Cons:
- Requires the image to load before fetching dimensions
- Limited browser support in old IE versions
To demonstrate, here‘s a full example:
<!-- index.html -->
<img id="image" src="image.png">
<div id="dimensions"></div>
// main.js
const img = document.getElementById(‘image‘);
const dims = document.getElementById(‘dimensions‘);
img.onload = function() {
dims.innerText = `${img.naturalWidth} x ${img.naturalHeight}`;
}
This hooks the onload event to run a callback when the image finishes loading. Inside, it inserts the dimensions into the page.
Method 2: Load Image and Fetch Dimensions
This next approach preloads the image dynamically to fetch its height and width:
function getDimensions(src) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
resolve({
width: img.width,
height: img.height
});
}
img.src = src;
});
}
getDimensions(‘image.png‘).then(dimensions => {
console.log(dimensions); // {width: 500, height: 300}
});
Here‘s what it‘s doing:
- Create a new
Image()object - Assign
onloadcallback to fetch width/height - Set the
srcwhich starts image load - Return promise that resolves with dimensions
This gives you an asynchronous getDimensions() function to reuse anywhere.
Pros:
- Reusable function for fetching sizes
- Works for images not already in the DOM
- Doesn‘t depend on browser support
Cons:
- Requires more code to implement
- Forces image to load before getting dimensions
Overall, it separates concerns for when you need more control over the loading.
Method 3: Draw Image on Canvas
The last technique renders the image on an invisible <canvas> element. This unlocks extra properties for detecting dimensions:
function getDimensions(src) {
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
const canvas = document.createElement(‘canvas‘);
const ctx = canvas.getContext(‘2d‘);
ctx.drawImage(img, 0, 0);
resolve({
width: canvas.width,
height: canvas.height
});
}
img.src = src;
});
}
getDimensions(‘image.tiff‘).then(dimensions => {
console.log(dimensions);
});
By drawing the image onto the canvas, you can fetch attributes like canvas.width without waiting for the entire image to load.
Pros
- Gets dimensions even for uncompressed images like TIFFs
- Fast – doesn‘t require full image load
Cons:
- More complex code
- Requires canvas support
This unlocks optimizations like showing placeholders while heavy images load.
Browser Support
The naturalWidth/naturalHeight properties work in all modern browsers. Issues arise in IE6 through 8.
Using the onload callbacks has no compatibility issues. All JavaScript environments directly support loading images.
Canvas is supported in IE9 and above. Using it limits your reach to older browsers.
Overall, all techniques work reliably across 95%+ of visitors. Unless you have a legacy audience, you won‘t run into problems.
Dimensions for Responsive Design
Understanding image sizes becomes even more critical for responsive web design.
You often want to serve differently sized images across device sizes. Or scale them dynamically with CSS as the viewport changes.
Here are some examples using the techniques covered:
Conditional image loading
function getWindowWidth() {
return window.innerWidth;
}
getDimensions(‘bg-image.jpg‘).then(dimensions => {
if(getWindowWidth() < 768) {
return ‘bg-image-mobile.jpg‘;
}
document.body.style.background = `url(bg-image.jpg) no-repeat 0 0 / ${dimensions.width}px ${dimensions.height}px`;
});
This customizes the background image based on mobile vs desktop sizes.
Fluid image resizing
img {
max-width: 100%;
height: auto;
}
Setting a flexible max-width keeps images proportionally scaled. height: auto instructs the browser to calculate the appropriate height.
Tips for Optimization
Here are some final best practices for working with images:
- Set dimension attributes – Adds width/height ahead of time for proper page layout and loading states.
- Compress images – Use tools like TinyPNG to optimize file sizes, improving load times.
- Lazy load offscreen – Images outside the device viewport can load lazily to accelerate performance.
- Serve next-gen formats – Newer types like JPEG 2000 and WebP reduce sizes with better compression and alpha channels.
Hopefully this guide gives you a thorough grasp of how to access image dimensions with JavaScript! Let me know if you have any other questions.


