Skip to content

Instantly share code, notes, and snippets.

@kohnmd
Created April 13, 2014 17:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kohnmd/10593739 to your computer and use it in GitHub Desktop.
Save kohnmd/10593739 to your computer and use it in GitHub Desktop.
Scale canvas element for high DPI monitors.
/**
* 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