Skip to content

Instantly share code, notes, and snippets.

@junhua
Forked from netcell/PhaserFillscreen.js
Created April 2, 2018 06:43
Show Gist options
  • Save junhua/46bd80820719ca5a96b18945fbf4b90e to your computer and use it in GitHub Desktop.
Save junhua/46bd80820719ca5a96b18945fbf4b90e to your computer and use it in GitHub Desktop.
Setting for Phaser.js to fill the screen on web browsers and Cocoon.js

This gist support scaling Phaser game to fill the screen on mobile game and web browser without stretching. The approach is fixing one of the measures (width or height) and then set the other measure accordingly to keep the aspect ratio.

NOTICE: This won't resize the canvas on window resize (device rotated).

As default, the height is fixed with FIXED_MEASURE = 'Height'. Set FIXED_MEASURE = 'Width' to set width as the fixed measure.

Change FIXED_SIZE to scale the game bigger or smaller. Meaning more pixels to render or less, while the canvas would still fill the screen.

/** Config part */
var FIXED_SIZE = 600;
var FIXED_MEASURE = 'Height';
/** Name maping */
var fixedName = FIXED_MEASURE;
var resName = fixedName === 'Height' ? 'Width' : 'Height';
var FIXED_NAME = fixedName.toUpperCase();
var RES_NAME = resName.toUpperCase();
/** Measures of document */
var documentElement = document.documentElement;
var documentFixed = documentElement['client' + fixedName];
var documentRes = documentElement['client' + resName];
var ratio = documentRes / documentFixed;
/** Canvas measures */
var canvasFixed = FIXED_SIZE;
var canvasRes = FIXED_SIZE * ratio;
var screen = {};
screen['CANVAS_' + FIXED_NAME] = canvasFixed;
screen['CANVAS_' + RES_NAME] = canvasRes;
/* Fix for CocoonJS */
window.width = navigator.isCocoonJS ? window.innerWidth : screen.CANVAS_WIDTH;
window.height = navigator.isCocoonJS ? window.innerHeight : screen.CANVAS_HEIGHT;
var game = module.exports = new Phaser.Game(screen.CANVAS_WIDTH, screen.CANVAS_HEIGHT, Phaser.CANVAS, 'game');
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
this.scale.pageAlignHorizontally = true;
this.scale.pageAlignVertically = true;
this.game.scale.refresh();
* {
margin : 0;
padding : 0;
}
html, body {
overflow : hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment