naturalWidth is a read-only image property that reports the intrinsic, density-corrected width of the loaded image in CSS pixels. It is different from the rendered width, which can change because of attributes, CSS or JavaScript.
const value = document.getElementById('i1').naturalWidth;
If CSS or JavaScript changes the displayed size, naturalWidth still reports the intrinsic width of the loaded image. If the intrinsic size is not yet available, it can be 0.
const image = document.getElementById('i1');
image.addEventListener('load', () => {
console.log(image.naturalWidth);
});
image.width = image.naturalWidth;
image.height = image.naturalHeight;
Demo resetting image to naturalWidth / natural size
Demo changing height and width
Demo resetting to naturalHeight and naturalWidth
Reading naturalHeight of Image Image Object
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.