Skip to content

Instantly share code, notes, and snippets.

@remarkablemark
Last active October 13, 2019 18:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save remarkablemark/e42a98ef7e8b1b109d298f16b8278262 to your computer and use it in GitHub Desktop.
Save remarkablemark/e42a98ef7e8b1b109d298f16b8278262 to your computer and use it in GitHub Desktop.
Helper function that resizes or scales a Phaser game canvas.
/**
* 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