Skip to content

Instantly share code, notes, and snippets.

@zachstronaut
Created August 31, 2011 22:22
Show Gist options
  • Save zachstronaut/1184900 to your computer and use it in GitHub Desktop.
Save zachstronaut/1184900 to your computer and use it in GitHub Desktop.
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 + ');');
}
}
@agrothe
Copy link

agrothe commented Oct 15, 2013

FYI, jsfiddle of this is here: http://jsfiddle.net/XAB3Y/

The function works ok, but could use some tweaks, like removing scroll bars, etc.

@formigone
Copy link

This causes antialiasing. Any way around that?

@yckart
Copy link

yckart commented Apr 29, 2016

The scale part in 73 bytes...

Math.min(window.innerWidth/canvas.width,window.innerHeight/canvas.height)

@agrothe Removing scroll bars, is usually done with

body { margin: 0 }
canvas { display: block }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment