Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Stretch HTML5 canvas to fill window, preserving aspect ratio
/**
* fullscreenify()
* Stretch canvas to size of window.
*
* Zachary Johnson
* http://www.zachstronaut.com/
*
* See also: https://gist.github.com/1178522
*/
window.addEventListener(
'load',
function () {
var canvas = document.getElementsByTagName('canvas')[0];
fullscreenify(canvas);
},
false
);
function fullscreenify(canvas) {
var style = canvas.getAttribute('style') || '';
window.addEventListener('resize', function () {resize(canvas);}, false);
resize(canvas);
function resize(canvas) {
var scale = {x: 1, y: 1};
scale.x = (window.innerWidth - 10) / canvas.width;
scale.y = (window.innerHeight - 10) / canvas.height;
if (scale.x < 1 || scale.y < 1) {
scale = '1, 1';
} else if (scale.x < scale.y) {
scale = scale.x + ', ' + scale.x;
} else {
scale = scale.y + ', ' + scale.y;
}
canvas.setAttribute('style', style + ' ' + '-ms-transform-origin: center top; -webkit-transform-origin: center top; -moz-transform-origin: center top; -o-transform-origin: center top; transform-origin: center top; -ms-transform: scale(' + scale + '); -webkit-transform: scale3d(' + scale + ', 1); -moz-transform: scale(' + scale + '); -o-transform: scale(' + scale + '); transform: scale(' + scale + ');');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.