Skip to content

Instantly share code, notes, and snippets.

@eczn
Forked from callumlocke/scale-canvas.ts
Created January 19, 2024 09:59
Show Gist options
  • Save eczn/fb151fff115fff8d6d1a87c7f6607a04 to your computer and use it in GitHub Desktop.
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.
/*
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)
@eczn
Copy link
Author

eczn commented Jan 19, 2024

最佳实践,fork 永久收藏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment