Skip to content

Instantly share code, notes, and snippets.

@mlshv
Created October 10, 2022 12:16
Show Gist options
  • Save mlshv/cde7908f35fa0da9e292de646dfe77f6 to your computer and use it in GitHub Desktop.
Save mlshv/cde7908f35fa0da9e292de646dfe77f6 to your computer and use it in GitHub Desktop.
High DPI canvas that respects device pixel ratio
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