Help illustration

Keep pressing the buttons, then reset to the natural dimensions.

Return to tutorial on Image naturalHeight | Image naturalWidth

JavaScript

const image = document.getElementById('i1');
const message = document.getElementById('msg');

function showSize() {
  message.textContent = `Rendered: ${image.width} × ${image.height}; Natural: ${image.naturalWidth} × ${image.naturalHeight}`;
}

function resize(direction) {
  if (direction === 'up' && image.width < 300) image.width *= 2;
  if (direction === 'down' && image.width > 5) image.width = Math.max(5, Math.round(image.width / 2));
  showSize();
}

document.getElementById('expand').addEventListener('click', () => resize('up'));
document.getElementById('compress').addEventListener('click', () => resize('down'));
document.getElementById('resetNatural').addEventListener('click', () => {
  image.width = image.naturalWidth;
  image.height = image.naturalHeight;
  showSize();
});
image.addEventListener('load', showSize);
if (image.complete) showSize();

HTML

<img src="images/help.jpg" id="i1" alt="Help illustration">
<button type="button" id="expand">Expand</button>
<button type="button" id="compress">Compress</button>
<button type="button" id="resetNatural">Reset to NaturalWidth & naturalHeight</button>
<div id="msg" aria-live="polite"></div>

Complete working page

<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Natural image dimensions</title></head><body>
<img src="images/help.jpg" id="i1" alt="Help illustration">
<button type="button" id="expand">Expand</button>
<button type="button" id="compress">Compress</button>
<button type="button" id="resetNatural">Reset to NaturalWidth & naturalHeight</button>
<div id="msg" aria-live="polite"></div>
<script>
const image = document.getElementById('i1');
const message = document.getElementById('msg');

function showSize() {
  message.textContent = `Rendered: ${image.width} × ${image.height}; Natural: ${image.naturalWidth} × ${image.naturalHeight}`;
}

function resize(direction) {
  if (direction === 'up' && image.width < 300) image.width *= 2;
  if (direction === 'down' && image.width > 5) image.width = Math.max(5, Math.round(image.width / 2));
  showSize();
}

document.getElementById('expand').addEventListener('click', () => resize('up'));
document.getElementById('compress').addEventListener('click', () => resize('down'));
document.getElementById('resetNatural').addEventListener('click', () => {
  image.width = image.naturalWidth;
  image.height = image.naturalHeight;
  showSize();
});
image.addEventListener('load', showSize);
if (image.complete) showSize();
</script></body></html>