Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.