Last active
April 20, 2023 08:48
-
-
Save jonikorpi/dff5f9dd47567f74be63855c87c3ed99 to your computer and use it in GitHub Desktop.
Resize canvas to match actual device pixels… mostly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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