srcset and naturalWidth/naturalHeight issues
HTML
<!-- The image is intrinsically 800x600. Its container is 200px wide. -->
<div class="frame">
<span class="label-width">200px sizes="auto"</span>
<div class="row">
<span class="label-height">150px</span>
<div class="box">
<img id="auto" sizes="auto" loading="lazy"
srcset="https://dummyimage.com/800x600/3366cc/ffffff.png&text=800x600 800w"
src="https://dummyimage.com/800x600/3366cc/ffffff.png&text=800x600">
</div>
</div>
</div>
<div class="frame">
<span class="label-width">200px sizes="700px"</span>
<div class="row">
<span class="label-height">150px</span>
<div class="box">
<!-- Control: explicit sizes="700px" -> naturalWidth is the true 800 -->
<img id="explicit" sizes="700px" loading="lazy"
srcset="https://dummyimage.com/800x600/cc3366/ffffff.png&text=800x600 700w"
src="https://dummyimage.com/800x600/cc3366/ffffff.png&text=800x600">
</div>
</div>
</div>
<div class="frame">
<span class="label-width">200px no sizes</span>
<div class="row">
<span class="label-height">150px</span>
<div class="box">
<!-- No sizes -->
<img id="control"
src="https://dummyimage.com/800x600/00FF00/ffffff.png&text=800x600">
</div>
</div>
</div>
<pre id="out">running…</pre>
CSS
body { padding: 40px; font-family: sans-serif; }
.frame {
display: inline-block;
padding: 28px 0 0 48px; /* room for the width (top) and height (left) labels */
margin-bottom: 40px;
}
.frame .label-width {
display: block;
width: 200px;
text-align: center;
font: 12px/1 monospace;
color: #555;
border-bottom: 1px solid #bbb;
padding-bottom: 4px;
margin-bottom: 8px;
}
.frame .row { display: flex; align-items: stretch; }
.frame .label-height {
writing-mode: vertical-rl;
transform: rotate(180deg);
text-align: center;
font: 12px/1 monospace;
color: #555;
border-right: 1px solid #bbb;
padding-right: 4px;
margin-right: 8px;
}
.box { width: 200px; }
img { width: 100%; height: auto; display: block; }
#out { font: 13px/1.6 monospace; white-space: pre-wrap; background:#111; color:#0f0; padding:12px; }
JavaScript
async function read(id) {
const img = document.getElementById(id);
try { await img.decode(); } catch (e) {}
return { naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight };
}
window.addEventListener('load', async () => {
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
const a = await read('auto');
const e = await read('explicit');
const c = await read('control');
document.getElementById('out').textContent =
'sizes="auto" -> naturalWidth=' + a.naturalWidth + ' naturalHeight=' + a.naturalHeight +
' (container=200px wide; file is 800x600 -> BUG)\n' +
'sizes="700px" -> naturalWidth=' + e.naturalWidth + ' naturalHeight=' + e.naturalHeight +
' (exactly as sizes/srcset)\n' +
'no sizes -> naturalWidth=' + c.naturalWidth + ' naturalHeight=' + c.naturalHeight +
' (control; correct true intrinsic size)\n\nUA: '
+ navigator.userAgent;
});