Skip to content

Instantly share code, notes, and snippets.

@mhkeller
Created May 11, 2018 23:04
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 mhkeller/271d40ba9963d40930d8763bd4d482d4 to your computer and use it in GitHub Desktop.
Save mhkeller/271d40ba9963d40930d8763bd4d482d4 to your computer and use it in GitHub Desktop.
/**
* 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 (ctx, width, height) {
// assume the device pixel ratio is 1 if the browser doesn't specify it
var devicePixelRatio = window.devicePixelRatio || 1;
var canvas = ctx.canvas;
// determine the 'backing store ratio' of the canvas ctx
var backingStoreRatio = (
ctx.webkitBackingStorePixelRatio ||
ctx.mozBackingStorePixelRatio ||
ctx.msBackingStorePixelRatio ||
ctx.oBackingStorePixelRatio ||
ctx.backingStorePixelRatio || 1
);
// determine the actual ratio we want to draw at
var 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 ctx so everything will work at the higher ratio
ctx.scale(ratio, ratio);
return {w: canvas.width, h: canvas.height};
}
scaleCanvas(ctx, width, height);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment