Skip to content

Instantly share code, notes, and snippets.

@jonikorpi
Last active April 20, 2023 08:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonikorpi/dff5f9dd47567f74be63855c87c3ed99 to your computer and use it in GitHub Desktop.
Save jonikorpi/dff5f9dd47567f74be63855c87c3ed99 to your computer and use it in GitHub Desktop.
Resize canvas to match actual device pixels… mostly
const observer = new ResizeObserver((entries) => {
const entry = entries[0];
if (entry.devicePixelContentBoxSize) {
canvas.width = entry.devicePixelContentBoxSize[0].inlineSize;
canvas.height = entry.devicePixelContentBoxSize[0].blockSize;
} else if (entry.contentBoxSize) {
// Annoying fallback. Assumes window.devicePixelRatio includes browser zoom.
// Currently that's how it works in Chrome, but not in Safari.
// As a result current Safari will end up with the wrong size if browser zoom is in use.
canvas.width = Math.round(entry.contentBoxSize[0].inlineSize * window.devicePixelRatio);
canvas.height = Math.round(entry.contentBoxSize[0].blockSize * window.devicePixelRatio);
}
gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
});
try {
observer.observe(canvas, { box: "device-pixel-content-box" });
} catch {
observer.observe(canvas);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment