Skip to content

Instantly share code, notes, and snippets.

@callumlocke
Last active April 12, 2024 03:25
Show Gist options
  • Save callumlocke/cc258a193839691f60dd to your computer and use it in GitHub Desktop.
Save callumlocke/cc258a193839691f60dd 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)
@atlasan
Copy link

atlasan commented Mar 8, 2023

This worked better for me because it scale the context too! :

function createHiPPICanvas(width, height) {
    const ratio = window.devicePixelRatio;
    const canvas = document.createElement("canvas");
    canvas.width = width * ratio;
    canvas.height = height * ratio;
    canvas.style.width = width + "px";
    canvas.style.height = height + "px";
    canvas.getContext("2d").scale(ratio, ratio);
    return canvas;
}

from https://stackoverflow.com/questions/15661339/how-do-i-fix-blurry-text-in-my-html5-canvas

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