Skip to content

Instantly share code, notes, and snippets.

@greggman
Created August 9, 2025 23:04
Show Gist options
  • Save greggman/c2df2760c6d119d812a601c413c722c7 to your computer and use it in GitHub Desktop.
Save greggman/c2df2760c6d119d812a601c413c722c7 to your computer and use it in GitHub Desktop.
Checking ResizeObserver devicePixelContentBoxSize
body {
background-color: white;
}
#container {
display: flex;
width: 199.5px;
}
canvas {
flex: 1 1 auto;
min-width: 0;
width: 100%;
height: 100px;
display: block;
}
<div id="container"><canvas></canvas><canvas></canvas></div>
const observer = new ResizeObserver(entries => {
console.log(entries.map(e => {
render(e.target);
return `inlineSize: ${e.devicePixelContentBoxSize[0].inlineSize}, width: ${Math.round(e.target.getBoundingClientRect().width * devicePixelRatio)}`;
}));
});
document.querySelectorAll('canvas').forEach(
elem => observer.observe(elem, { box: 'device-pixel-content-box' }));
function render(canvas) {
const ctx = canvas.getContext('2d');
ctx.strokeRect(0.5, 0.5, ctx.canvas.width - 1, ctx.canvas.height - 1);
const width = Math.round(ctx.canvas.getBoundingClientRect().width * devicePixelRatio);
try {
const x = width - 1;
console.log(x);
const id = ctx.getImageData(x + 1000, 0, 1, 1);
} catch (e) {
console.error(e);
}
}
{"name":"Checking ResizeObserver devicePixelContentBoxSize","settings":{},"filenames":["index.html","index.css","index.js"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment