Skip to content

Instantly share code, notes, and snippets.

@dg1234uk
Last active July 2, 2023 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dg1234uk/3e9cd32ccfb9a6f969c5 to your computer and use it in GitHub Desktop.
Save dg1234uk/3e9cd32ccfb9a6f969c5 to your computer and use it in GitHub Desktop.
TypeScript function that creates a High DPI Canvas.
function createHighDPICanvas(width: number, height: number, parentElement = document.body) {
// Validate inputs
if (typeof width !== 'number' || typeof height !== 'number') {
throw new Error("Width and height must be numbers");
}
// Create a new HTML canvas element
const canvas = document.createElement("canvas");
// Set the width and height of the canvas in CSS pixels
canvas.style.width = `${width}px`;
canvas.style.height = `${height}px`;
// Add the canvas to the body of the document
parentElement.appendChild(canvas);
// Get the Device Pixel Ratio (DPR) of the screen. This is usually 1 for standard screens, and higher (e.g. 2) for high DPI screens like Retina displays.
const dpr = window.devicePixelRatio || 1;
// Get the dimensions of the canvas in CSS pixels
const rect = canvas.getBoundingClientRect();
// Set the actual width and height of the canvas in pixels. This is the number of pixels in the canvas bitmap.
// For high DPI screens, this will be greater than the size in CSS pixels, to prevent the canvas from appearing blurry.
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Get the 2D rendering context for the canvas
const ctx = canvas.getContext("2d");
// Throw an error if the context could not be obtained
if (!ctx) {
throw new Error("Could not get canvas context");
}
// Scale all drawing operations on the context by the DPR. This means that when we use coordinates in CSS pixels in our drawing code,
// they will be automatically converted to the correct number of screen pixels.
ctx.scale(dpr, dpr);
// Return the canvas and context so they can be used elsewhere
return { canvas, ctx };
}
// Create a high DPI canvas with the specified size, and get the canvas and its context
const { canvas, ctx } = createHighDPICanvas(WIDTH, HEIGHT, PARENT_ELEMENT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment