-
-
Save eczn/fb151fff115fff8d6d1a87c7f6607a04 to your computer and use it in GitHub Desktop.
How to fix a canvas so it will look good on retina/high-DPI screens.
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
/* | |
UPDATED for 2023 - Now much simpler. The old tricks are no longer needed. | |
The following code makes an 800×600 canvas that is always as sharp as possible for the device. | |
You still draw on it as if it's the logical size (800×600 in this case), but everything just | |
looks sharper on high-DPI screens. Regular non-sharp screens are not affected. | |
*/ | |
const width = 800 | |
const height = 600 | |
const canvas = document.createElement('canvas') | |
const ctx = canvas.getContext('2d') | |
// 1. Multiply the canvas's width and height by the devicePixelRatio | |
const ratio = window.devicePixelRatio || 1 | |
canvas.width = width * ratio | |
canvas.height = height * ratio | |
// 2. Force it to display at the original (logical) size with CSS or style attributes | |
canvas.style.width = width + 'px' | |
canvas.style.height = height + 'px' | |
// 3. Scale the context so you can draw on it without considering the ratio. | |
ctx.scale(ratio, ratio) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
最佳实践,fork 永久收藏