Last active
October 13, 2019 18:20
-
-
Save remarkablemark/e42a98ef7e8b1b109d298f16b8278262 to your computer and use it in GitHub Desktop.
Helper function that resizes or scales a Phaser game canvas.
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
/** | |
* Adds resize listener for game canvas. | |
* | |
* @example | |
* var game = new Phaser.Game(config); | |
* addResizeListener(game); | |
* | |
* @param {Phaser.Game} game - The game object. | |
* @param {HTMLCanvasElement} game.canvas - The canvas element. | |
* @return {Function} - The resize listener. | |
*/ | |
function addResizeListener(game) { | |
/** | |
* Resizes the game canvas. | |
*/ | |
function resize() { | |
var canvas = game.canvas; | |
var width; | |
var height; | |
if (window.innerWidth) { | |
// use browser dimensions | |
width = window.innerWidth; | |
height = window.innerHeight; | |
} else { | |
// otherwise fallback to device dimensions | |
width = window.screen.width; | |
height = window.screen.height; | |
} | |
// calculate aspect ratios | |
var windowRatio = width / height; | |
var gameRatio = canvas.width / canvas.height; | |
var newWidth; | |
var newHeight; | |
// resize depending on aspect ratio | |
if (windowRatio < gameRatio) { | |
newWidth = width; | |
newHeight = width / gameRatio; | |
} else { | |
newWidth = height * gameRatio; | |
newHeight = height; | |
} | |
canvas.style.width = newWidth + 'px'; | |
canvas.style.height = newHeight + 'px'; | |
} | |
// resize and add event listener on load or else canvas will be undefined | |
document.addEventListener('DOMContentLoaded', function() { | |
resize(); | |
window.addEventListener('resize', resize); | |
}); | |
return resize; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment