360 Secure SkillHub
360 安全技能中心

game-setup-and-config

系统讲解 Phaser 4 的 GameConfig 默认值与 v3 差异,覆盖 WebGL 和 Canvas 渲染器选择、像素渲染键、帧率限制、插件、启动顺序、游戏事件、暂停与销毁,并给出代码示例和常见陷阱。

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

安装

发给 Agent
帮我安装这个技能:npx secure-skills-cli add phaserjs/phaser/game-setup-and-config
兼容性
通用兼容
联网要求
不联网
数据出网
数据不出本机
Metadata
name
game-setup-and-config
description
Create and configure a Phaser 4 game: new Phaser.Game, the GameConfig and its typedefs, the renderer type and the AUTO fallback to Canvas, render keys (pixelArt, smoothPixelArt, roundPixels, sdfShapes, alphaStrategy, stencil), fps.limit and setFPSLimit, global and Scene plugins, the boot order, game events, pause and destroy. Use when starting a new game, choosing WebGL or Canvas, setting the size or background, capping the frame rate, adding a plugin, hot reloading with Vite, or reacting to the tab being hidden. Corrects v3 habits: the default size is 1024x768, not 800x600; roundPixels defaults to false; fps.target doesn't cap the frame rate; Phaser.WEBGL throws instead of falling back. Triggers on: new Phaser.Game, GameConfig, config, renderer, WebGL, Canvas, pixelArt, FPS, plugin, preBoot, postBoot, game.destroy, hot reload.
metadata
{"phaser-version":"4.3.0"}

Game setup and config

How to create a Phaser.Game: the config keys that matter in v4, the renderer, the frame rate, plugins, the boot order and the game's own events.

Source: src/core/Config.js (every key and its default), src/core/Game.js, src/core/CreateRenderer.js, src/core/TimeStep.js, src/core/typedefs/. Related: phaser4-core, scale-and-responsive, scenes, loading-assets.

Quick start

import Phaser from 'phaser';

class Game extends Phaser.Scene
{
    constructor ()
    {
        super('Game');
    }

    create ()
    {
        this.add.text(this.scale.width / 2, this.scale.height / 2, 'Hello').setOrigin(0.5);
    }
}

const game = new Phaser.Game({
    type: Phaser.AUTO,
    width: 1024,
    height: 768,
    parent: 'game-container',
    backgroundColor: '#1d1d1d',
    scene: [ Game ]
});
  • import Phaser from 'phaser' works from 4.1. In 4.0, use import * as Phaser from 'phaser'.
  • Only the first Scene in scene starts. The others start only if their Scene config has active: true, or when you start them. See scenes.
  • parent is an element or its id. If you leave it out, the canvas goes in document.body. With null, Phaser doesn't add the canvas to the page at all.
  • A key in the scale object, such as width, height, zoom or parent, overrides the same key at the top level. A key in the render object, such as pixelArt, does the same. Set each key in one place.

Where the keys are

Each sub-object has a typedef in src/core/typedefs/ listing every key and its default. Read it rather than guessing.

Key Typedef Covered in
scale ScaleConfig.js scale-and-responsive
render (or top level) RenderConfig.js Below
fps FPSConfig.js Below
input InputConfig.js, KeyboardInputConfig.js, MouseInputConfig.js, TouchInputConfig.js, GamepadInputConfig.js input-keyboard-mouse-touch
loader LoaderConfig.js loading-assets
physics PhysicsConfig.js physics-arcade, physics-matter
plugins PluginObject.js, PluginObjectItem.js Below
audio AudioConfig.js: disableWebAudio, noAudio, context audio-and-sound
dom DOMContainerConfig.js: createContainer, pointerEvents Below
callbacks CallbacksConfig.js: preBoot, postBoot Below
filters FiltersConfig.js: glow.quality, glow.distance (both 10) filters-and-postfx
images ImagesConfig.js: the default, missing and white textures
banner BannerConfig.js. false hides the console banner

Other top-level keys: title, version and url (shown in the banner), seed (for Phaser.Math.RND), autoFocus (true), disableContextMenu (false), transparent, canvas, context, canvasStyle, customEnvironment.

Renderer

type
Phaser.AUTO (0, the default) WebGL if the browser has it. Since 4.3, if the WebGL Renderer can't be created, it falls back to Canvas
Phaser.WEBGL (2) WebGL only. Throws if it can't be created
Phaser.CANVAS (1) Canvas. Deprecated in v4: many features are WebGL only
Phaser.HEADLESS (3) No renderer, for tests. Still needs a DOM
  • On the 4.3 fallback, Phaser logs Could not create WebGL Renderer, falling back to CanvasRenderer: with the reason, and gives the Canvas Renderer a new canvas. This happens on devices which report WebGL, then fail to make a context or lack an extension.
  • So code written for AUTO can run in Canvas. Check the renderer you got: this.renderer.type === Phaser.WEBGL in a Scene, or game.config.renderType, which is updated by the fallback. Guard the WebGL-only features: see phaser4-core.
  • If you pass your own canvas, or set customEnvironment: true, AUTO throws Must set explicit renderType in custom environment. Use Phaser.WEBGL or Phaser.CANVAS.
  • window.FORCE_WEBGL or window.FORCE_CANVAS, set before the game is made, override type. This is useful for testing the Canvas path.
  • Context loss: the WebGL Renderer emits Phaser.Renderer.Events.LOSE_WEBGL and RESTORE_WEBGL on this.renderer, and restores its own resources. Phaser.Core.Events.CONTEXT_LOST is never emitted.

Render keys

Set these at the top level or in render. All are in RenderConfig.js.

Key Default Notes
pixelArt false Sets antialias and antialiasGL to false and roundPixels to true. For 1:1 pixels
smoothPixelArt false WebGL. Sets antialias to true and pixelArt to false. Keeps big pixels crisp but smooths their edges when scaled or rotated
antialias, antialiasGL true Texture filtering, and the WebGL context's antialias
roundPixels false It was true in v3. See phaser4-core
transparent false Forces the background to alpha 0, whatever backgroundColor is
sdfShapes true 4.3, WebGL. Graphics and Shapes draw circles, rounded rectangles, lines and stroked paths as signed distance fields. false draws triangles, as before 4.3. See graphics-and-shapes
alphaStrategy 'keep' 4.2. 'dither' or a number threshold discards fragments instead of blending them
stencil true 4.2. false saves framebuffer memory, but Stencil can't be used
stencilAlphaStrategy 'dither' 4.2. How stencils treat transparent pixels. See masks-and-stencils
mipmapFilter '' Set it only to make mipmaps, e.g. 'LINEAR_MIPMAP_LINEAR'
mipmapRegeneration false 4.1. Mipmaps for framebuffers (filters, DynamicTextures). Expensive
maxLights 10 Lights per Camera. See lighting
selfShadow false Default self-shadowing for lit objects
skipUnreadyShaders false Skip objects whose shader is still compiling, instead of stalling
renderNodes {} Custom render nodes. See custom-rendering

Less often changed: batchSize (16384), maxTextures (-1, all), autoMobileTextures (true), pathDetailThreshold (1), powerPreference ('default'), preserveDrawingBuffer, premultipliedAlpha (true), clearBeforeRender (true), failIfMajorPerformanceCaveat, desynchronized.

For pixel art, pixelArt: true sets the texture flags, and the scale config decides how the canvas is scaled up. scale.zoom is ignored by FIT and the other scaled modes. See scale-and-responsive and docs/Phaser 4 Pixel Art Guide/.

Frame rate

fps: {
    limit: 30,      // cap the frame rate; 0 (the default) means no cap
    target: 60      // the default; it doesn't cap anything
}
  • limit caps the frame rate. A limit above the display's refresh rate does nothing.
  • target doesn't cap the rate. It is the setTimeout rate when forceSetTimeOut: true, and the cap on the delta while the window is blurred.
  • Change the limit at run time with this.game.loop.setFPSLimit(30) (4.2). 0 removes it. Don't set fpsLimit directly.
  • 4.3 fixed the delta under a limit (#7393). It was too high, so game time ran fast, by about 1.4 times with a limit of 91 on a 75Hz display. A game tuned with a limit before 4.3 now runs at the correct, slower speed.
  • Other keys: min (5), forceSetTimeOut (false), deltaHistory (10), panicMax (120), smoothStep (true). this.game.loop.actualFps is the measured rate.

Plugins

A global plugin has one instance for the game. A Scene plugin has one instance per Scene.

class Scores extends Phaser.Plugins.BasePlugin
{
    constructor (pluginManager)
    {
        super(pluginManager);

        this.best = 0;
    }
}

class Aim extends Phaser.Plugins.ScenePlugin
{
    boot ()
    {
        //  Runs once, when the Scene boots. this.scene and this.systems are set
    }
}

const game = new Phaser.Game({
    width: 1024,
    height: 768,
    plugins: {
        global: [ { key: 'Scores', plugin: Scores, start: true, mapping: 'scores' } ],
        scene: [ { key: 'Aim', plugin: Aim, mapping: 'aim' } ]
    }
});

//  In any Scene: this.scores.best and this.aim

//  Vite hot reload: destroy the old game when this module is replaced
if (import.meta.hot)
{
    import.meta.hot.dispose(() => game.destroy(true));
}
  • A global plugin with a mapping is always started, and is set as this.<mapping> in every Scene. Without one, use this.plugins.get('Scores').
  • plugins.default replaces the list of default Scene plugins, and plugins.defaultMerge adds to it. A Scene can also list its plugins in its own config.
  • To load a plugin file at run time: this.load.plugin(key, url, start, mapping) and this.load.scenePlugin(key, url, systemKey, sceneKey).
  • Since 4.3, the Plugin Manager boots on the game's BOOT event for every renderer, and Scenes can't start before it has. So a global plugin with a mapping is in every Scene with HEADLESS and in jsdom tests too, where it wasn't before (#7348).
  • Since 4.3, each Plugin Manager tracks the global plugins it installed (#7151). A new game made before the old one is destroyed, as in hot reload, gets its plugins, and two games on one page can run the same global plugin. Before, the new game skipped them with Plugin key in use.

Boot order

  1. new Phaser.Game(config) parses the config and makes the managers, including game.registry, game.loop and game.plugins. Nothing is drawn yet.
  2. When the DOM is ready, boot() calls callbacks.preBoot(game), creates the renderer, adds the canvas to the page, then emits Phaser.Core.Events.BOOT. The Plugin, Texture, Scale and Input Managers boot on BOOT.
  3. When the default textures are ready, the game emits READY, and the Scene Manager starts the Scenes.
  4. Then callbacks.postBoot(game) runs, and the game loop starts.

So postBoot runs after the first Scene's init, and after its create if it has no preload. To give the first Scene some data, set it in preBoot:

callbacks: {
    preBoot: (game) => game.registry.set('level', 1)
}

Game events, pause and destroy

this.game.events outlives every Scene, so remove your listeners on SHUTDOWN:

create ()
{
    const save = () => localStorage.setItem('level', String(this.registry.get('level')));

    this.game.events.on(Phaser.Core.Events.HIDDEN, save);

    this.events.once(Phaser.Scenes.Events.SHUTDOWN, () =>
    {
        this.game.events.off(Phaser.Core.Events.HIDDEN, save);
    });
}
  • Phaser.Core.Events: BLUR, FOCUS, HIDDEN, VISIBLE, PAUSE, RESUME, BOOT, READY, DESTROY, and PRE_STEP, STEP, POST_STEP, PRE_RENDER, POST_RENDER each frame.
  • When the page is hidden, the loop pauses and the game emits PAUSE. When it is visible again, it emits RESUME, with how long it was paused. game.pause() and game.resume() emit the same events, but game.isPaused is set only by game.pause().
  • BLUR doesn't pause anything. It caps the delta until FOCUS.
  • game.pause() stops every Scene's update and render. To pause only the gameplay, pause its Scene. See scenes.
  • game.destroy(removeCanvas, noReturn = false) is done on the next frame, after which DESTROY is emitted. Pass noReturn: true only if no Phaser game will be made on this page again.

Other config

  • Input: input: false doesn't turn input off; it is ignored. Use input: { keyboard: false, mouse: false, touch: false }. Gamepads need input: { gamepad: true }. Right-click games need disableContextMenu: true.
  • DOM Elements: this.add.dom() needs dom: { createContainer: true } and a parent. The container is always above the canvas. dom.behindCanvas was removed in 4.3, as it never did anything.
  • Loader: loader.baseURL, path, prefix, crossOrigin, maxParallelDownloads (32, or 6 on Android), maxRetries (5) and others set the defaults for every Scene's Loader. loader.prefix was read by the Loader but not set by the config until 4.3. A Scene's own loader config overrides them.
  • Physics: physics: { default: 'arcade', arcade: { gravity: { y: 300 } } }. With no default, this.physics exists only in Scenes whose own config sets physics.

Gotchas

  • The default size is 1024x768. Set width and height, and position by this.scale.width and this.scale.height.
  • Phaser.WEBGL throws if WebGL fails. Phaser.AUTO falls back to Canvas, where WebGL-only features do nothing.
  • fps.target doesn't cap the frame rate. fps.limit or setFPSLimit does.
  • scale.zoom with FIT does nothing. Pixel-art scaling is in scale-and-responsive.
  • transparent: true overrides backgroundColor.
  • input: false is ignored. Turn off each device.
  • Listen for Phaser.Renderer.Events.LOSE_WEBGL, not Phaser.Core.Events.CONTEXT_LOST, which is never emitted.
  • Listeners on this.game.events survive Scene restarts. Remove them on SHUTDOWN.