360 Secure SkillHub
360 安全技能中心

scale-and-responsive

该 Skill 面向 Phaser 4 游戏开发,说明 Scale Manager 的 FIT、RESIZE、EXPAND 等缩放模式,以及居中、全屏、屏幕方向、高 DPI、像素画整倍缩放和 CSS 变换处理,并列出 v3 习惯差异与监听器清理等常见陷阱。

分类:开发
phaserjs
热度 0.00
最近更新 2026-12-03 17:40:29

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/scale-and-responsive
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
scale-and-responsive
description
Fit a Phaser 4 game to the page with the Scale Manager (this.scale): the scale config, the modes FIT, RESIZE, EXPAND, ENVELOP and NONE, autoCenter, zoom and MAX_ZOOM, min, max and snap, the RESIZE event, fullscreen, orientation, pixel-art scaling, high-DPI screens and CSS-transformed canvases. Use when making a game responsive or full-window, letterboxing, laying out a HUD after a resize, adding a fullscreen button, showing a rotate-your-device message, or scaling pixel art by whole numbers. Corrects v3 habits: zoom is ignored by FIT; this.cameras.resize() in a resize handler breaks HUD and minimap Cameras; scale listeners leak across Scene restarts; isLandscape is false for landscape-secondary. Triggers on: ScaleManager, this.scale, responsive, resize, fullscreen, FIT, RESIZE, EXPAND, letterbox, orientation, MAX_ZOOM, pixel art scaling, devicePixelRatio.
metadata
{"phaser-version":"4.3.0"}

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
  • FIT is the usual choice. Everything inside the config size is always visible.
  • EXPAND also keeps the config size visible, but grows the game on one side instead of showing bars, so this.scale.width or height changes. Lay out the extra space on RESIZE.
  • RESIZE makes the canvas as big as the parent, so a big window means a lot of pixels to fill.
  • zoom is used only by NONE. 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, max and snap (each { width, height }) limit the scaled size. snap rounds it down to multiples.

The parent

  • The parent needs a size. An empty <div> is 0 pixels high. With expandParent: true (the default), the Scale Manager sets the parent's and the body's height to 100%. NONE doesn'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 width or height of '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 resizeInterval ms (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). gameSize is what your Scene works in.
  • RESIZE is emitted on every refresh, including in FIT, where only the display size changed. Check gameSize if 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. Calling resize would also make HUD and minimap Cameras full size.
  • Changing the size from code: setGameSize(width, height) in the scaled modes, resize(width, height) in NONE, and setParentSize(width, height) when parent is null. setZoom(n) and setSnap(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_ZOOM is the biggest whole number which fits the parent. If the parent has no height, it is 1.
  • setMaxZoom() emits RESIZE itself, so keep the check, or the handler loops.
  • This listener is on the game, outside any Scene, so it needs no SHUTDOWN removal.
  • FIT ignores zoom and scales by any ratio, so pixels come out uneven. To keep FIT but use whole steps, set snap and min to 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. See docs/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() or toggleFullscreen() 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.isFullscreen is the current state.
  • Without a fullscreenTarget in the config, Phaser moves the canvas into a new <div> and sends that fullscreen. A game in an iframe needs allowfullscreen on the iframe.
  • Events on this.scale: ENTER_FULLSCREEN, LEAVE_FULLSCREEN (also when the player presses Esc), FULLSCREEN_UNSUPPORTED, and FULLSCREEN_FAILED with the browser's fullscreenerror event. FULLSCREEN_FAILED is emitted from 4.3. Before that it was never emitted.
  • The iPhone browser has no Fullscreen API for elements, so fullscreen.available is false and startFullscreen emits FULLSCREEN_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.orientation is a string: 'landscape-primary', 'landscape-secondary', 'portrait-primary' or 'portrait-secondary'. The constants are Phaser.Scale.LANDSCAPE, LANDSCAPE_SECONDARY, PORTRAIT and PORTRAIT_SECONDARY.
  • Test with startsWith('landscape') or startsWith('portrait'). isLandscape, isPortrait and === Phaser.Scale.LANDSCAPE are only true for the -primary orientation, so an upside-down device reads as neither.
  • ORIENTATION_CHANGE is for the screen's orientation. A desktop window made tall doesn't change it. For the shape of the game, use isGamePortrait and isGameLandscape, or the RESIZE event.
  • lockOrientation() only tries the old screen.lockOrientation APIs, so it returns false in current browsers. Use screen.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

  • zoom does nothing in FIT, RESIZE, EXPAND and the other scaled modes.
  • NONE doesn't size the parent. An unsized parent gives a MAX_ZOOM of 1.
  • RESIZE fires on every refresh, not only when the game size changes.
  • this.scale listeners in a Scene need removing on SHUTDOWN.
  • Don't call this.cameras.resize() on resize.
  • isLandscape and isPortrait ignore the -secondary orientations.
  • Fullscreen from pointerdown fails on touch screens. Use pointer up.