Created
October 10, 2022 12:16
-
-
Save mlshv/cde7908f35fa0da9e292de646dfe77f6 to your computer and use it in GitHub Desktop.
High DPI canvas that respects device pixel ratio
This file contains hidden or 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 PIXEL_RATIO = (() => { | |
const ctx = document.createElement('canvas').getContext('2d') | |
if (ctx) { | |
const dpr = window.devicePixelRatio || 1 | |
const bsr = | |
ctx.webkitBackingStorePixelRatio || | |
ctx.mozBackingStorePixelRatio || | |
ctx.msBackingStorePixelRatio || | |
ctx.oBackingStorePixelRatio || | |
ctx.backingStorePixelRatio || | |
1 | |
return dpr / bsr | |
} | |
return null | |
})() | |
function createHiDPICanvas(w, h, canvas = document.createElement('canvas'), ratio = PIXEL_RATIO) { | |
canvas.width = w * ratio | |
canvas.height = h * ratio | |
canvas.style.width = w + 'px' | |
canvas.style.height = h + 'px' | |
canvas.getContext('2d').setTransform(ratio, 0, 0, ratio, 0, 0) | |
return canvas | |
} | |
export default createHiDPICanvas |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment