Skip to content

Instantly share code, notes, and snippets.

@MikuroXina
Last active June 7, 2023 06:17
Show Gist options
  • Select an option

  • Save MikuroXina/0426ae5129edd373088c344f781d2268 to your computer and use it in GitHub Desktop.

Select an option

Save MikuroXina/0426ae5129edd373088c344f781d2268 to your computer and use it in GitHub Desktop.
Make `<canvas>` prepared for more pixel density display.
/**
* Make `<canvas>` prepared for more pixel density display and returns a 2D rendering context.
*
* @param canvas {HTMLCanvasElement} - To be preapared.
* @param devicePixelRatio {number} - The pixel ratio by device.
* @returns {Canvas2DRenderingContext} - The scaled 2D rendering context.
*/
export function setupCanvas(canvas, devicePixelRatio) {
const { width, height } = canvas;
canvas.width *= devicePixelRatio;
canvas.height *= devicePixelRatio;
canvas.style.width = width + "px";
canvas.style.height = height + "px";
const ctx = canvas.getContext("2d");
ctx.scale(devicePixelRatio, devicePixelRatio);
return ctx;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment