Scale and responsive
How the Scale Manager sizes the canvas to the page, how to react to a resize, fullscreen, orientation, and scaling pixel art by whole numbers.
Source: src/scale/ScaleManager.js, src/scale/const/, src/scale/events/, src/core/typedefs/ScaleConfig.js. Related: game-setup-and-config, cameras, phaser4-core.
Quick start
new Phaser.Game({
type: Phaser.AUTO,
scale: {
parent: 'game-container',
mode: Phaser.Scale.FIT,
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 1280,
height: 720
}
});
The game is drawn at 1280x720, and the canvas is scaled with CSS to fit inside the parent, keeping its aspect ratio. this.scale.width and this.scale.height stay 1280x720.
Modes
Phaser.Scale.FIT is short for Phaser.Scale.ScaleModes.FIT, and the same goes for the centre and zoom constants.
| Mode | The game size | The canvas |
|---|---|---|
NONE (0, the default) |
The config size | Game size × zoom. No other scaling |
FIT (3) |
The config size | Scaled to fit inside the parent. Letterboxed |
ENVELOP (4) |
The config size | Scaled to cover the parent. Cropped |
WIDTH_CONTROLS_HEIGHT (1), HEIGHT_CONTROLS_WIDTH (2) |
The config size | One side follows the parent; the other keeps the aspect ratio |
RESIZE (5) |
The parent size | The parent size, unscaled |
EXPAND (6) |
The config size, grown on one side to match the parent's aspect ratio | Scaled to fill the parent |
FITis the usual choice. Everything inside the config size is always visible.EXPANDalso keeps the config size visible, but grows the game on one side instead of showing bars, sothis.scale.widthorheightchanges. Lay out the extra space onRESIZE.RESIZEmakes the canvas as big as the parent, so a big window means a lot of pixels to fill.zoomis used only byNONE. The other modes size the canvas from the parent and ignore it.autoCenter:NO_CENTER(0),CENTER_BOTH(1),CENTER_HORIZONTALLY(2),CENTER_VERTICALLY(3). It sets the canvas margins.min,maxandsnap(each{ width, height }) limit the scaled size.snaprounds it down to multiples.
The parent
- The parent needs a size. An empty
<div>is 0 pixels high. WithexpandParent: true(the default), the Scale Manager sets the parent's and the body's height to 100%.NONEdoesn't do this, so give the parent a CSS size yourself. - Padding on the parent isn't allowed for. Put it on a wrapper.
- Don't size or position the canvas with your own CSS. The Scale Manager sets its width, height and margins.
- A
widthorheightof'100%'is read once, at boot. - A window resize is picked up at once. A change to the parent alone is picked up by a poll every
resizeIntervalms (500). - Since 4.3, a scrolled page no longer makes the Scale Manager refresh every 500 ms (#7203).
Reacting to a resize
The Scale Manager belongs to the game, so a listener on it outlives the Scene. Remove it on SHUTDOWN, or it is added again on every restart:
create ()
{
const score = this.add.text(0, 16, 'Score: 0').setOrigin(1, 0);
const layout = (gameSize) =>
{
score.x = gameSize.width - 16;
};
layout(this.scale.gameSize);
this.scale.on(Phaser.Scale.Events.RESIZE, layout);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.scale.off(Phaser.Scale.Events.RESIZE, layout);
});
}
- The arguments are
(gameSize, baseSize, displaySize, previousWidth, previousHeight).gameSizeis what your Scene works in. RESIZEis emitted on every refresh, including inFIT, where only the display size changed. CheckgameSizeif you only care about the game size.- Don't call
this.cameras.resize()in the handler. The Camera Manager already resizes every Camera which was at (0, 0) and the full size of the game. Callingresizewould also make HUD and minimap Cameras full size. - Changing the size from code:
setGameSize(width, height)in the scaled modes,resize(width, height)inNONE, andsetParentSize(width, height)whenparentisnull.setZoom(n)andsetSnap(w, h)also exist.
Pixel art
Give each game pixel a whole number of screen pixels. Use NONE with MAX_ZOOM and pixelArt: true:
const game = new Phaser.Game({
pixelArt: true,
scale: {
parent: 'game-container', // give it a CSS size, such as 100vw x 100vh
mode: Phaser.Scale.NONE,
autoCenter: Phaser.Scale.CENTER_BOTH,
width: 320,
height: 240,
zoom: Phaser.Scale.MAX_ZOOM
}
});
// MAX_ZOOM is worked out once, at boot. Work it out again when the parent changes size.
game.scale.on(Phaser.Scale.Events.RESIZE, () =>
{
if (game.scale.getMaxZoom() !== game.scale.zoom)
{
game.scale.setMaxZoom();
}
});
MAX_ZOOMis the biggest whole number which fits the parent. If the parent has no height, it is 1.setMaxZoom()emitsRESIZEitself, so keep the check, or the handler loops.- This listener is on the game, outside any Scene, so it needs no
SHUTDOWNremoval. FITignoreszoomand scales by any ratio, so pixels come out uneven. To keepFITbut use whole steps, setsnapandminto the game size:snap: { width: 320, height: 240 }, min: { width: 320, height: 240 }.- If your art is scaled or rotated in the game,
smoothPixelArt: true(WebGL) with a larger game size keeps the pixels crisp without jagged edges. Seedocs/Phaser 4 Pixel Art Guide/.
High-DPI screens
v4 has no resolution setting. In FIT, a game size bigger than its CSS size looks sharp, because the browser scales the canvas down. For example, a 1920x1080 game shown at 960x540 CSS pixels draws one game pixel per screen pixel on a 2x display. RESIZE matches CSS pixels, so it looks soft on a 2x display.
Fullscreen
const button = this.add.text(this.scale.width - 16, 16, 'Fullscreen').setOrigin(1, 0).setInteractive();
button.setVisible(this.scale.fullscreen.available);
button.on(Phaser.Input.Events.GAMEOBJECT_POINTER_UP, () =>
{
this.scale.toggleFullscreen();
});
- Call
startFullscreen(),stopFullscreen()ortoggleFullscreen()from a pointer-up handler. Browsers allow fullscreen only from a user gesture, and on touch screens a touch counts only when it ends. Phaser's input handlers run inside the browser's event, so they count. startFullscreen(options)defaults to{ navigationUI: 'hide' }.this.scale.isFullscreenis the current state.- Without a
fullscreenTargetin the config, Phaser moves the canvas into a new<div>and sends that fullscreen. A game in an iframe needsallowfullscreenon the iframe. - Events on
this.scale:ENTER_FULLSCREEN,LEAVE_FULLSCREEN(also when the player presses Esc),FULLSCREEN_UNSUPPORTED, andFULLSCREEN_FAILEDwith the browser'sfullscreenerrorevent.FULLSCREEN_FAILEDis emitted from 4.3. Before that it was never emitted. - The iPhone browser has no Fullscreen API for elements, so
fullscreen.availableisfalseandstartFullscreenemitsFULLSCREEN_UNSUPPORTED.
Orientation
create ()
{
const message = this.add.text(this.scale.width / 2, this.scale.height / 2, 'Please rotate your device').setOrigin(0.5);
const check = (orientation) =>
{
message.setVisible(orientation.startsWith('portrait'));
};
check(this.scale.orientation);
this.scale.on(Phaser.Scale.Events.ORIENTATION_CHANGE, check);
this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
{
this.scale.off(Phaser.Scale.Events.ORIENTATION_CHANGE, check);
});
}
this.scale.orientationis a string:'landscape-primary','landscape-secondary','portrait-primary'or'portrait-secondary'. The constants arePhaser.Scale.LANDSCAPE,LANDSCAPE_SECONDARY,PORTRAITandPORTRAIT_SECONDARY.- Test with
startsWith('landscape')orstartsWith('portrait').isLandscape,isPortraitand=== Phaser.Scale.LANDSCAPEare only true for the-primaryorientation, so an upside-down device reads as neither. ORIENTATION_CHANGEis for the screen's orientation. A desktop window made tall doesn't change it. For the shape of the game, useisGamePortraitandisGameLandscape, or theRESIZEevent.lockOrientation()only tries the oldscreen.lockOrientationAPIs, so it returnsfalsein current browsers. Usescreen.orientation.lock('landscape'), which returns a promise, usually needs fullscreen, and isn't on iOS. Catch its rejection.
CSS transforms
Since 4.3, pointer positions are right when the canvas, or an element around it, has a 2D CSS transform, such as rotate(90deg) to force landscape in a portrait WebView (#7278). If you change the transform at run time, call this.scale.refresh(). 3D transforms and perspective aren't supported. this.scale.transformXY(pageX, pageY, output) converts page coordinates to game coordinates the same way.
Gotchas
zoomdoes nothing inFIT,RESIZE,EXPANDand the other scaled modes.NONEdoesn't size the parent. An unsized parent gives aMAX_ZOOMof 1.RESIZEfires on every refresh, not only when the game size changes.this.scalelisteners in a Scene need removing onSHUTDOWN.- Don't call
this.cameras.resize()on resize. isLandscapeandisPortraitignore the-secondaryorientations.- Fullscreen from
pointerdownfails on touch screens. Use pointer up.
