Skip to content

Instantly share code, notes, and snippets.

@anandanand84
Forked from callumlocke/scale-canvas.ts
Created March 24, 2017 02:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anandanand84/e6bb002a97a71d17fe421476ccb3f938 to your computer and use it in GitHub Desktop.
Save anandanand84/e6bb002a97a71d17fe421476ccb3f938 to your computer and use it in GitHub Desktop.
Function to fix a canvas so it will look good on retina/hi-DPI screens.
/**
* This function takes a canvas, context, width and height. It scales both the
* canvas and the context in such a way that everything you draw will be as
* sharp as possible for the device.
*
* It doesn't return anything, it just modifies whatever canvas and context you
* pass in.
*
* Adapted from Paul Lewis's code here:
* http://www.html5rocks.com/en/tutorials/canvas/hidpi/
*/
export default function scaleCanvas(canvas, context, width, height) {
// assume the device pixel ratio is 1 if the browser doesn't specify it
const devicePixelRatio = window.devicePixelRatio || 1;
// determine the 'backing store ratio' of the canvas context
const backingStoreRatio = (
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1
);
// determine the actual ratio we want to draw at
const ratio = devicePixelRatio / backingStoreRatio;
if (devicePixelRatio !== backingStoreRatio) {
// set the 'real' canvas size to the higher width/height
canvas.width = width * ratio;
canvas.height = height * ratio;
// ...then scale it back down with CSS
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
}
else {
// this is a normal 1:1 device; just scale it simply
canvas.width = width;
canvas.height = height;
canvas.style.width = '';
canvas.style.height = '';
}
// scale the drawing context so everything will work at the higher ratio
context.scale(ratio, ratio);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment