Created
August 31, 2011 22:22
-
-
Save zachstronaut/1184900 to your computer and use it in GitHub Desktop.
Stretch HTML5 canvas to fill window, preserving aspect ratio
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
/** | |
* 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 + ');'); | |
} | |
} |
FYI, jsfiddle of this is here: http://jsfiddle.net/XAB3Y/
The function works ok, but could use some tweaks, like removing scroll bars, etc.
This causes antialiasing. Any way around that?
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
Hi Zachstronaut - do you have this implemented anywhere to see it working?