Home >Web Front-end >JS Tutorial >How Can I Get an Image's Width and Height Using JavaScript?
Retrieving Image Dimensions with JavaScript
Do you need a way to determine the dimensions of an image on a web page? JavaScript provides a simple solution for this task.
Getting Image Size
To programmatically obtain image dimensions, utilize the following JavaScript code:
const img = new Image(); img.onload = function() { alert(this.width + 'x' + this.height); } img.src = 'http://www.google.com/intl/en_ALL/images/logo.gif';
In this snippet, a new Image object is created. The onload event listener is assigned to process the image once it has finished loading. The listener then retrieves the width and height properties of the image object, which represent the dimensions of the image.
For DOM Images
For images already present in the DOM, you can directly access their width and height properties:
const img = document.getElementById('my-image'); alert(img.offsetWidth + 'x' + img.offsetHeight);
Considerations
Keep in mind that this approach requires the image to be loaded before retrieving its dimensions. For images that are dynamically loaded or not immediately visible, you may need to ensure they have fully loaded before accessing their properties.
The above is the detailed content of How Can I Get an Image's Width and Height Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!