JavaScript Image Object

The JavaScript HTMLImageElement object represents an HTML <img> element. Once you select an image, you can read its displayed size, intrinsic size, alternative text, position, source and other properties, or update supported properties when an interaction requires it.

const image = document.getElementById('my_image');
Table of Contents

Working image example Top ↑

plus2net.com tutorial site
<img src="../images/top2.jpg" alt="plus2net.com tutorial site" id="my_image" width="150" height="30">

The values below are generated from that image object. Resize the browser window and the window dimensions update automatically. The original tutorial also linked to the HTML <body> tag reference; that link is retained here.


const image = document.getElementById('my_image');
const output = document.getElementById('imageDetails');

function showImageDetails() {
  const rows = [
    `Height: ${image.height}`,
    `Width: ${image.width}`,
    `naturalHeight: ${image.naturalHeight}`,
    `naturalWidth: ${image.naturalWidth}`,
    `Alt text: ${image.alt}`,
    `offsetTop: ${image.offsetTop}`,
    `offsetLeft: ${image.offsetLeft}`,
    `window.innerWidth: ${window.innerWidth}`,
    `window.innerHeight: ${window.innerHeight}`,
  ];
  output.textContent = rows.join('\n');
}

image.addEventListener('load', showImageDetails);
window.addEventListener('resize', showImageDetails);
if (image.complete) showImageDetails();

Important image properties Top ↑

PropertyPurpose
altAlternative text for the image.
heightThe rendered height in CSS pixels.
widthThe rendered width in CSS pixels.
naturalWidthThe intrinsic, density-corrected width of the loaded image.
naturalHeightThe intrinsic, density-corrected height of the loaded image.
PositionChanging image position with CSS.
OffsetsReading the image position relative to its offset container.
AlignHistorical image alignment property; CSS layout is preferred.
BorderHistorical image border property; CSS borders are preferred.

Displayed size vs natural size Top ↑

width and height describe the size at which the image is currently drawn. naturalWidth and naturalHeight describe the image's intrinsic dimensions after it has loaded.

console.log(image.width, image.height);
console.log(image.naturalWidth, image.naturalHeight);

Legacy presentation properties Top ↑

The original tutorial also demonstrated the HTML image align and border properties. Those remain linked above for historical/search value, but new pages should normally use CSS such as float, flex/grid layout and border.

Applications and Demo scripts using Image Object in JavaScript Top ↑




Subscribe to our YouTube Channel here



plus2net.com










We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer