Created
April 13, 2014 17:28
-
-
Save kohnmd/10593739 to your computer and use it in GitHub Desktop.
Scale canvas element for high DPI monitors.
This file contains hidden or 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
/** | |
* Resizes the canvas for high DPI (retina) screens. | |
* | |
* Modified from here: http://www.html5rocks.com/en/tutorials/canvas/hidpi/ | |
* | |
* By Paul Lewis, customized by Mike Kohn | |
*/ | |
var HDPICanvas = (function() { | |
function scale(canvas) { | |
var context = canvas.getContext('2d'); | |
var devicePixelRatio = window.devicePixelRatio || 1; | |
var backingStoreRatio = context.webkitBackingStorePixelRatio || | |
context.mozBackingStorePixelRatio || | |
context.msBackingStorePixelRatio || | |
context.oBackingStorePixelRatio || | |
context.backingStorePixelRatio || 1; | |
var ratio = devicePixelRatio / backingStoreRatio; | |
if (devicePixelRatio !== backingStoreRatio) { | |
var oldWidth = canvas.width; | |
var oldHeight = canvas.height; | |
canvas.width = oldWidth * ratio; | |
canvas.height = oldHeight * ratio; | |
canvas.style.width = oldWidth + 'px'; | |
canvas.style.height = oldHeight + 'px'; | |
// now scale the context to counter | |
// the fact that we've manually scaled | |
// our canvas element | |
context.scale(ratio, ratio); | |
} | |
return ratio; | |
} | |
return { | |
scale: scale | |
}; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment