Created
May 11, 2018 23:04
-
-
Save mhkeller/271d40ba9963d40930d8763bd4d482d4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
scaleCanvas(ctx, width, height); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment