scale-and-responsive

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Scale and Responsive Design

缩放与响应式设计

How to use the ScaleManager for scaling, centering, fullscreen, orientation handling, and responsive resize in Phaser 4.
Key source paths:
src/scale/ScaleManager.js
,
src/scale/const/
,
src/scale/events/
,
src/core/typedefs/ScaleConfig.js
Related skills: ../game-setup-and-config/SKILL.md
如何在Phaser 4中使用ScaleManager实现缩放、居中、全屏、方向处理和响应式窗口调整。
核心源码路径:
src/scale/ScaleManager.js
src/scale/const/
src/scale/events/
src/core/typedefs/ScaleConfig.js
相关技能: ../game-setup-and-config/SKILL.md

Quick Start

快速入门

Scale-to-fit with centering -- the most common setup for responsive games:
js
const config = {
    type: Phaser.AUTO,
    scale: {
        parent: 'game-container',
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        width: 800,
        height: 600
    },
    scene: MyScene
};

const game = new Phaser.Game(config);
The
scale
config object is parsed into a
Phaser.Core.Config
instance which the
ScaleManager
reads during boot. The ScaleManager sets the canvas element size and applies CSS scaling to fit it within its parent.
带居中的适配缩放——响应式游戏最常用的设置:
js
const config = {
    type: Phaser.AUTO,
    scale: {
        parent: 'game-container',
        mode: Phaser.Scale.FIT,
        autoCenter: Phaser.Scale.CENTER_BOTH,
        width: 800,
        height: 600
    },
    scene: MyScene
};

const game = new Phaser.Game(config);
scale
配置对象会被解析为
Phaser.Core.Config
实例,ScaleManager会在启动时读取该实例。ScaleManager会设置canvas元素的尺寸,并应用CSS缩放使其适配父容器。

Core Concepts

核心概念

ScaleManager (src/scale/ScaleManager.js)

ScaleManager(src/scale/ScaleManager.js)

The ScaleManager is created during the Game boot sequence and is accessible at
game.scale
or
this.scale
from within a Scene. It extends
EventEmitter
.
Three internal Size components drive all calculations:
ComponentPropertyPurpose
gameSize
game.scale.gameSize
The unmodified game dimensions from config. Used for world bounds, cameras. Read via
game.scale.width
/
game.scale.height
.
baseSize
game.scale.baseSize
The auto-rounded gameSize. Sets the actual
canvas.width
and
canvas.height
attributes.
displaySize
game.scale.displaySize
The CSS-scaled canvas size after applying scale mode, parent bounds, and zoom. Sets
canvas.style.width
/
canvas.style.height
.
Scaling works by keeping the canvas element dimensions fixed (baseSize) and stretching it via CSS properties (displaySize). This is equivalent to CSS
transform-scale
but without browser prefix issues.
The
displayScale
property (
Phaser.Math.Vector2
) holds the ratio
baseSize / canvasBounds
and is used internally for input coordinate transformation.
ScaleManager在游戏启动过程中创建,可通过
game.scale
或场景内的
this.scale
访问。它继承自
EventEmitter
所有计算由三个内部Size组件驱动:
组件属性用途
gameSize
game.scale.gameSize
配置中未修改的游戏尺寸,用于世界边界、相机设置。可通过
game.scale.width
/
game.scale.height
读取。
baseSize
game.scale.baseSize
自动取整后的gameSize,设置实际的
canvas.width
canvas.height
属性。
displaySize
game.scale.displaySize
应用缩放模式、父容器边界和缩放后的CSS缩放canvas尺寸,设置
canvas.style.width
/
canvas.style.height
缩放的原理是保持canvas元素尺寸固定(baseSize),通过CSS属性(displaySize)拉伸它。这等效于CSS的
transform-scale
,但不会有浏览器前缀问题。
displayScale
属性(
Phaser.Math.Vector2
)存储
baseSize / canvasBounds
的比例,内部用于输入坐标转换。

Scale Modes (src/scale/const/SCALE_MODE_CONST.js)

缩放模式(src/scale/const/SCALE_MODE_CONST.js)

All modes are on
Phaser.Scale.ScaleModes
and are set via
scale.mode
in config:
ConstantValueBehavior
NONE
0No automatic scaling. Canvas uses config width/height. You manage sizing yourself. If you resize the canvas externally, call
game.scale.resize(w, h)
to update internals.
WIDTH_CONTROLS_HEIGHT
1Height adjusts automatically to maintain aspect ratio based on width.
HEIGHT_CONTROLS_WIDTH
2Width adjusts automatically to maintain aspect ratio based on height.
FIT
3Scales to fit inside parent while preserving aspect ratio. May leave empty space (letterbox/pillarbox). Most commonly used mode.
ENVELOP
4Scales to cover the entire parent while preserving aspect ratio. May extend beyond parent bounds (content gets cropped).
RESIZE
5Canvas element itself is resized to fill parent. No CSS scaling -- 1:1 pixel mapping. The
gameSize
,
baseSize
, and
displaySize
all change to match parent. Beware of GPU fill-rate on large displays.
EXPAND
6Hybrid of RESIZE and FIT. The visible area resizes to fill the parent, and the canvas scales to fit inside that area. Added in v3.80.
Shorthand constants are also available directly on
Phaser.Scale
:
Phaser.Scale.FIT
,
Phaser.Scale.RESIZE
, etc.
所有模式都在
Phaser.Scale.ScaleModes
上,可通过配置中的
scale.mode
设置:
常量行为
NONE
0无自动缩放,canvas使用配置的宽高。需自行管理尺寸。如果外部调整canvas大小,需调用
game.scale.resize(w, h)
更新内部状态。
WIDTH_CONTROLS_HEIGHT
1根据宽度自动调整高度,保持宽高比。
HEIGHT_CONTROLS_WIDTH
2根据高度自动调整宽度,保持宽高比。
FIT
3在保持宽高比的同时缩放以适配父容器,可能会留下空白区域(黑边),是最常用的模式。
ENVELOP
4在保持宽高比的同时缩放以覆盖整个父容器,可能超出父容器边界(内容会被裁剪)。
RESIZE
5canvas元素本身调整大小以填充父容器,无CSS缩放——像素1:1映射。
gameSize
baseSize
displaySize
都会变为与父容器一致。注意大尺寸显示器上的GPU填充率问题。
EXPAND
6RESIZE和FIT的混合模式,可视区域调整大小以填充父容器,canvas缩放以适配该区域,在v3.80版本新增。
简写常量也可直接在
Phaser.Scale
上使用:
Phaser.Scale.FIT
Phaser.Scale.RESIZE
等。

Center Modes (src/scale/const/CENTER_CONST.js)

居中模式(src/scale/const/CENTER_CONST.js)

Set via
scale.autoCenter
in config. Centering is achieved by setting CSS
marginLeft
and
marginTop
on the canvas:
ConstantValueBehavior
NO_CENTER
0No auto-centering (default).
CENTER_BOTH
1Center horizontally and vertically within parent.
CENTER_HORIZONTALLY
2Center horizontally only.
CENTER_VERTICALLY
3Center vertically only.
The parent element must have calculable bounds. If the parent has no defined width/height, centering will not work correctly.
通过配置中的
scale.autoCenter
设置,居中是通过设置canvas的CSS
marginLeft
marginTop
实现的:
常量行为
NO_CENTER
0无自动居中(默认)。
CENTER_BOTH
1在父容器内水平和垂直居中。
CENTER_HORIZONTALLY
2仅水平居中。
CENTER_VERTICALLY
3仅垂直居中。
父元素必须有可计算的边界,如果父元素没有定义宽高,居中将无法正常工作。

Zoom (src/scale/const/ZOOM_CONST.js)

缩放(src/scale/const/ZOOM_CONST.js)

Set via
scale.zoom
in config. Multiplies the display size:
ConstantValueBehavior
NO_ZOOM
1No zoom (default).
ZOOM_2X
22x zoom -- good for pixel art at low base resolution.
ZOOM_4X
44x zoom.
MAX_ZOOM
-1Automatically calculates the largest integer zoom that fits in the parent.
You can also pass any numeric value. The zoom affects CSS display size but not the canvas resolution.
通过配置中的
scale.zoom
设置,会乘以显示尺寸:
常量行为
NO_ZOOM
1无缩放(默认)。
ZOOM_2X
22倍缩放——适合低基础分辨率的像素画。
ZOOM_4X
44倍缩放。
MAX_ZOOM
-1自动计算适配父容器的最大整数缩放比例。
也可以传入任何数值,缩放会影响CSS显示尺寸,但不会改变canvas分辨率。

Orientation (src/scale/const/ORIENTATION_CONST.js)

方向(src/scale/const/ORIENTATION_CONST.js)

Read via
game.scale.orientation
. Values are strings:
  • Phaser.Scale.Orientation.LANDSCAPE
    =
    'landscape-primary'
  • Phaser.Scale.Orientation.LANDSCAPE_SECONDARY
    =
    'landscape-secondary'
  • Phaser.Scale.Orientation.PORTRAIT
    =
    'portrait-primary'
  • Phaser.Scale.Orientation.PORTRAIT_SECONDARY
    =
    'portrait-secondary'
Convenience booleans:
game.scale.isPortrait
,
game.scale.isLandscape
(device orientation),
game.scale.isGamePortrait
,
game.scale.isGameLandscape
(game dimensions).
可通过
game.scale.orientation
读取,值为字符串:
  • Phaser.Scale.Orientation.LANDSCAPE
    =
    'landscape-primary'
  • Phaser.Scale.Orientation.LANDSCAPE_SECONDARY
    =
    'landscape-secondary'
  • Phaser.Scale.Orientation.PORTRAIT
    =
    'portrait-primary'
  • Phaser.Scale.Orientation.PORTRAIT_SECONDARY
    =
    'portrait-secondary'
便捷布尔值:
game.scale.isPortrait
game.scale.isLandscape
(设备方向)、
game.scale.isGamePortrait
game.scale.isGameLandscape
(游戏尺寸方向)。

Common Patterns

常见模式

FIT Mode with Centering (Most Common)

带居中的FIT模式(最常用)

js
scale: {
    parent: 'game-container',
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 1280,
    height: 720
}
The game maintains its 16:9 aspect ratio and centers within the parent. Empty space appears as letterbox/pillarbox bars. Style the parent's background color to control bar appearance.
js
scale: {
    parent: 'game-container',
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 1280,
    height: 720
}
游戏保持16:9的宽高比并在父容器内居中,空白区域会显示为黑边,可通过设置父容器的背景色控制黑边外观。

Responsive Resize (Dynamic Canvas Size)

响应式窗口调整(动态Canvas尺寸)

js
scale: {
    parent: 'game-container',
    mode: Phaser.Scale.RESIZE,
    width: '100%',
    height: '100%'
}
js
// In your scene -- respond to size changes:
create() {
    this.scale.on('resize', this.handleResize, this);
}

handleResize(gameSize, baseSize, displaySize) {
    this.cameras.resize(gameSize.width, gameSize.height);
    // Reposition UI elements based on new dimensions
}
Width/height accept percentage strings (e.g.,
'100%'
) which resolve against the parent size. If the parent has no size, they fall back to
window.innerWidth
/
window.innerHeight
.
js
scale: {
    parent: 'game-container',
    mode: Phaser.Scale.RESIZE,
    width: '100%',
    height: '100%'
}
js
// 在场景中——响应尺寸变化:
create() {
    this.scale.on('resize', this.handleResize, this);
}

handleResize(gameSize, baseSize, displaySize) {
    this.cameras.resize(gameSize.width, gameSize.height);
    // 根据新尺寸重新定位UI元素
}
宽/高支持百分比字符串(如
'100%'
),会根据父容器尺寸解析。如果父容器没有尺寸,会回退到
window.innerWidth
/
window.innerHeight

Fullscreen Toggle

全屏切换

js
// Must be called from a pointerup gesture (not pointerdown)
this.input.on('pointerup', () => {
    if (this.scale.isFullscreen) {
        this.scale.stopFullscreen();
    } else {
        this.scale.startFullscreen();
    }
});

// Or use the convenience method:
this.input.on('pointerup', () => {
    this.scale.toggleFullscreen();
});
  • startFullscreen(fullscreenOptions)
    -- requests browser fullscreen. Default options:
    { navigationUI: 'hide' }
    .
  • stopFullscreen()
    -- exits fullscreen mode.
  • toggleFullscreen(fullscreenOptions)
    -- toggles between the two.
  • isFullscreen
    -- read-only boolean for current state.
If no
fullscreenTarget
is configured, Phaser creates a temporary
<div>
, moves the canvas into it, and sends that div fullscreen. The div is removed when leaving fullscreen.
For iframes, the
allowfullscreen
attribute is required.
js
// 必须从pointerup手势调用(不能是pointerdown)
this.input.on('pointerup', () => {
    if (this.scale.isFullscreen) {
        this.scale.stopFullscreen();
    } else {
        this.scale.startFullscreen();
    }
});

// 或者使用便捷方法:
this.input.on('pointerup', () => {
    this.scale.toggleFullscreen();
});
  • startFullscreen(fullscreenOptions)
    ——请求浏览器全屏,默认选项:
    { navigationUI: 'hide' }
  • stopFullscreen()
    ——退出全屏模式。
  • toggleFullscreen(fullscreenOptions)
    ——在两种状态间切换。
  • isFullscreen
    ——只读布尔值,表示当前状态。
如果未配置
fullscreenTarget
,Phaser会创建一个临时
<div>
,将canvas移入其中并将该div设为全屏,退出全屏时会移除该div。
对于iframe,需要
allowfullscreen
属性。

Mobile Orientation Handling

移动端方向处理

js
create() {
    this.scale.on('orientationchange', (orientation) => {
        if (orientation === Phaser.Scale.LANDSCAPE) {
            // Show game UI
        } else {
            // Show "rotate device" message
        }
    });

    // Lock orientation (mobile browsers only, limited support):
    this.scale.lockOrientation('landscape');
}
js
create() {
    this.scale.on('orientationchange', (orientation) => {
        if (orientation === Phaser.Scale.LANDSCAPE) {
            // 显示游戏UI
        } else {
            // 显示"旋转设备"提示
        }
    });

    // 锁定方向(仅移动端浏览器,支持有限):
    this.scale.lockOrientation('landscape');
}

Fixed Size (No Scaling)

固定尺寸(无缩放)

js
scale: {
    mode: Phaser.Scale.NONE,
    width: 800,
    height: 600
}
In NONE mode, if you change the canvas size externally you must call
game.scale.resize(newWidth, newHeight)
to update all internal components including input coordinates.
js
scale: {
    mode: Phaser.Scale.NONE,
    width: 800,
    height: 600
}
在NONE模式下,如果外部修改canvas尺寸,必须调用
game.scale.resize(newWidth, newHeight)
更新所有内部组件,包括输入坐标。

Pixel Art with Max Zoom

带最大缩放的像素画

js
scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 320,
    height: 240,
    zoom: Phaser.Scale.MAX_ZOOM
},
pixelArt: true
MAX_ZOOM
calculates the largest integer multiplier that fits in the parent. Combined with
pixelArt: true
(which disables anti-aliasing), this gives crisp pixel rendering.
js
scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 320,
    height: 240,
    zoom: Phaser.Scale.MAX_ZOOM
},
pixelArt: true
MAX_ZOOM
会计算适配父容器的最大整数倍数,结合
pixelArt: true
(禁用抗锯齿),可实现清晰的像素渲染。

Snap Values for Grid Alignment

网格对齐的吸附值

js
scale: {
    mode: Phaser.Scale.FIT,
    width: 800,
    height: 600,
    snap: { width: 16, height: 16 }
}
When the browser resizes, dimensions snap down to the nearest grid multiple (using floor). Best used with FIT mode. Can also be set at runtime:
game.scale.setSnap(16, 16)
or reset with
game.scale.setSnap()
.
js
scale: {
    mode: Phaser.Scale.FIT,
    width: 800,
    height: 600,
    snap: { width: 16, height: 16 }
}
浏览器调整大小时,尺寸会向下吸附到最近的网格倍数(使用floor计算),最适合FIT模式。也可在运行时设置:
game.scale.setSnap(16, 16)
,或使用
game.scale.setSnap()
重置。

Min/Max Size Constraints

最小/最大尺寸限制

js
scale: {
    mode: Phaser.Scale.FIT,
    width: 800,
    height: 600,
    min: { width: 400, height: 300 },
    max: { width: 1600, height: 1200 }
}
The display size is clamped to these bounds during scaling calculations.
js
scale: {
    mode: Phaser.Scale.FIT,
    width: 800,
    height: 600,
    min: { width: 400, height: 300 },
    max: { width: 1600, height: 1200 }
}
显示尺寸在缩放计算时会被限制在这些边界内。

Configuration Reference

配置参考

ScaleConfig (src/core/typedefs/ScaleConfig.js)

ScaleConfig(src/core/typedefs/ScaleConfig.js)

All properties go inside the
scale
object in your game config:
PropertyTypeDefaultDescription
width
number|string
1024
Base game width. Strings like
'100%'
resolve against parent size.
height
number|string
768
Base game height. Strings like
'100%'
resolve against parent size.
zoom
number|ZoomType
1
Canvas zoom factor. Use
Phaser.Scale.MAX_ZOOM
for auto.
parent
HTMLElement|string|null
undefined
Parent DOM element or its ID.
undefined
=
document.body
.
null
= no parent (you manage canvas placement).
expandParent
boolean
true
Allow ScaleManager to set parent/body CSS height to 100%.
mode
ScaleModeType
NONE
Scale mode constant (see table above).
min
{width, height}
-Minimum canvas dimensions.
max
{width, height}
-Maximum canvas dimensions.
snap
{width, height}
-Snap values for resize rounding.
autoRound
boolean
false
Floor display/style sizes for low-powered device performance.
autoCenter
CenterType
NO_CENTER
Auto-centering mode (see table above).
resizeInterval
number
500
Milliseconds between parent size checks (fallback polling).
fullscreenTarget
HTMLElement|string
undefined
Element to send fullscreen. If not set, Phaser creates a wrapper div.
所有属性都放在游戏配置的
scale
对象中:
属性类型默认值描述
width
number|string
1024
游戏基础宽度,
'100%'
这类字符串会根据父容器尺寸解析。
height
number|string
768
游戏基础高度,
'100%'
这类字符串会根据父容器尺寸解析。
zoom
number|ZoomType
1
Canvas缩放因子,使用
Phaser.Scale.MAX_ZOOM
可自动计算。
parent
HTMLElement|string|null
undefined
父DOM元素或其ID,
undefined
表示
document.body
null
表示无父容器(需自行管理canvas位置)。
expandParent
boolean
true
允许ScaleManager将父容器/body的CSS高度设置为100%。
mode
ScaleModeType
NONE
缩放模式常量(见上表)。
min
{width, height}
-Canvas最小尺寸。
max
{width, height}
-Canvas最大尺寸。
snap
{width, height}
-窗口调整时的取整吸附值。
autoRound
boolean
false
对显示/样式尺寸取整,提升低性能设备的运行表现。
autoCenter
CenterType
NO_CENTER
自动居中模式(见上表)。
resizeInterval
number
500
父容器尺寸检查的间隔毫秒数(备用轮询机制)。
fullscreenTarget
HTMLElement|string
undefined
要设为全屏的元素,如果未设置,Phaser会创建一个包装div。

Events (src/scale/events/)

事件(src/scale/events/)

All events are on
Phaser.Scale.Events
and are emitted by the ScaleManager instance (
game.scale
):
EventString ValueCallback SignatureWhen
RESIZE
'resize'
(gameSize, baseSize, displaySize, previousWidth, previousHeight)
Any resize, refresh, or scale change. The three Size parameters have
.width
,
.height
,
.aspectRatio
.
ORIENTATION_CHANGE
'orientationchange'
(orientation)
Device orientation changes.
orientation
is a string constant from
Phaser.Scale.Orientation
.
ENTER_FULLSCREEN
'enterfullscreen'
()
Browser successfully enters fullscreen.
LEAVE_FULLSCREEN
'leavefullscreen'
()
Browser leaves fullscreen (via code or user ESC).
FULLSCREEN_FAILED
'fullscreenfailed'
(error)
Fullscreen request was denied by the browser.
FULLSCREEN_UNSUPPORTED
'fullscreenunsupported'
()
Browser does not support the Fullscreen API.
所有事件都在
Phaser.Scale.Events
上,由ScaleManager实例(
game.scale
)触发:
事件字符串值回调签名触发时机
RESIZE
'resize'
(gameSize, baseSize, displaySize, previousWidth, previousHeight)
任何窗口调整、刷新或缩放变化时触发,三个Size参数包含
.width
.height
.aspectRatio
属性。
ORIENTATION_CHANGE
'orientationchange'
(orientation)
设备方向变化时触发,
orientation
Phaser.Scale.Orientation
中的字符串常量。
ENTER_FULLSCREEN
'enterfullscreen'
()
浏览器成功进入全屏时触发。
LEAVE_FULLSCREEN
'leavefullscreen'
()
浏览器退出全屏时触发(通过代码或用户按ESC键)。
FULLSCREEN_FAILED
'fullscreenfailed'
(error)
全屏请求被浏览器拒绝时触发。
FULLSCREEN_UNSUPPORTED
'fullscreenunsupported'
()
浏览器不支持全屏API时触发。

API Quick Reference

API快速参考

Key Properties (read-only unless noted)

关键属性(除非注明否则为只读)

PropertyTypeDescription
width
number
Game width (from
gameSize.width
).
height
number
Game height (from
gameSize.height
).
isFullscreen
boolean
Currently in fullscreen mode.
isPortrait
boolean
Device is in portrait orientation.
isLandscape
boolean
Device is in landscape orientation.
isGamePortrait
boolean
Game dimensions are taller than wide.
isGameLandscape
boolean
Game dimensions are wider than tall.
scaleMode
number
Current scale mode constant.
orientation
string
Current orientation string.
zoom
number
Current zoom factor.
autoRound
boolean
Whether sizes are auto-floored.
autoCenter
number
Current center mode constant.
parentSize
Size
Computed parent dimensions.
gameSize
Size
Unmodified game dimensions.
baseSize
Size
Canvas element dimensions.
displaySize
Size
CSS-scaled display dimensions.
displayScale
Vector2
Ratio of baseSize to canvasBounds (used for input mapping).
canvas
HTMLCanvasElement
The game canvas element.
canvasBounds
Rectangle
DOM bounding rect of the canvas.
parent
HTMLElement
The parent DOM element.
parentIsWindow
boolean
True if parent is
document.body
.
resizeInterval
number
Polling interval in ms (writable).
属性类型描述
width
number
游戏宽度(来自
gameSize.width
)。
height
number
游戏高度(来自
gameSize.height
)。
isFullscreen
boolean
当前是否处于全屏模式。
isPortrait
boolean
设备是否为竖屏方向。
isLandscape
boolean
设备是否为横屏方向。
isGamePortrait
boolean
游戏尺寸是否为竖屏(高大于宽)。
isGameLandscape
boolean
游戏尺寸是否为横屏(宽大于高)。
scaleMode
number
当前缩放模式常量。
orientation
string
当前方向字符串。
zoom
number
当前缩放因子。
autoRound
boolean
是否自动对尺寸取整。
autoCenter
number
当前居中模式常量。
parentSize
Size
计算后的父容器尺寸。
gameSize
Size
未修改的游戏尺寸。
baseSize
Size
Canvas元素尺寸。
displaySize
Size
CSS缩放后的显示尺寸。
displayScale
Vector2
baseSize与canvasBounds的比例(用于输入映射)。
canvas
HTMLCanvasElement
游戏canvas元素。
canvasBounds
Rectangle
Canvas的DOM边界矩形。
parent
HTMLElement
父DOM元素。
parentIsWindow
boolean
父容器是否为
document.body
resizeInterval
number
轮询间隔毫秒数(可写)。

Key Methods

关键方法

MethodReturnsDescription
resize(width, height)
this
For NONE mode: sets game, base, and display sizes directly. Updates canvas element and CSS.
setGameSize(width, height)
this
For scaled modes (FIT, etc.): changes the base game size and re-applies scaling.
setParentSize(width, height)
this
Manually set parent dimensions (useful when
parent: null
).
setZoom(value)
this
Change zoom factor at runtime.
setMaxZoom()
this
Set zoom to maximum integer that fits parent.
setSnap(snapWidth, snapHeight)
this
Set or reset snap grid values.
getMaxZoom()
number
Calculate (but don't apply) the max zoom.
getViewPort(camera?, out?)
Rectangle
Get the visible area rectangle, optionally for a specific camera.
refresh(prevW?, prevH?)
this
Force recalculation of scale, bounds, orientation. Emits RESIZE.
startFullscreen(options?)
void
Enter fullscreen. Must be called from
pointerup
.
stopFullscreen()
void
Exit fullscreen.
toggleFullscreen(options?)
void
Toggle fullscreen state.
lockOrientation(orientation)
boolean
Attempt to lock screen orientation (mobile only).
transformX(pageX)
number
Convert DOM pageX to game coordinate.
transformY(pageY)
number
Convert DOM pageY to game coordinate.
getParentBounds()
boolean
Recalculate parent size. Returns true if changed.
updateCenter()
void
Recalculate and apply centering margins.
updateBounds()
void
Update
canvasBounds
from the canvas bounding client rect.
方法返回值描述
resize(width, height)
this
适用于NONE模式:直接设置游戏、基础和显示尺寸,更新canvas元素和CSS。
setGameSize(width, height)
this
适用于缩放模式(如FIT等):修改基础游戏尺寸并重新应用缩放。
setParentSize(width, height)
this
手动设置父容器尺寸(当
parent: null
时有用)。
setZoom(value)
this
在运行时修改缩放因子。
setMaxZoom()
this
将缩放设置为适配父容器的最大整数比例。
setSnap(snapWidth, snapHeight)
this
设置或重置吸附网格值。
getMaxZoom()
number
计算(但不应用)最大缩放比例。
getViewPort(camera?, out?)
Rectangle
获取可视区域矩形,可指定特定相机。
refresh(prevW?, prevH?)
this
强制重新计算缩放、边界和方向,触发RESIZE事件。
startFullscreen(options?)
void
进入全屏,必须从
pointerup
调用。
stopFullscreen()
void
退出全屏。
toggleFullscreen(options?)
void
切换全屏状态。
lockOrientation(orientation)
boolean
尝试锁定屏幕方向(仅移动端)。
transformX(pageX)
number
将DOM的pageX转换为游戏坐标。
transformY(pageY)
number
将DOM的pageY转换为游戏坐标。
getParentBounds()
boolean
重新计算父容器尺寸,返回是否有变化。
updateCenter()
void
重新计算并应用居中边距。
updateBounds()
void
根据canvas的bounding client rect更新
canvasBounds

Gotchas

注意事项

  1. Parent element must have dimensions. The ScaleManager relies on the parent's computed CSS size. An unstyled
    <div>
    has zero height, which breaks centering and scaling. Either give it explicit CSS dimensions or let
    expandParent: true
    (the default) set body/parent to 100% height.
  2. No padding on the parent. The ScaleManager does not account for parent padding. Apply padding to a wrapper element instead, or use margins on the parent's parent.
  3. Do not style the canvas directly. The ScaleManager controls
    canvas.style.width
    ,
    canvas.style.height
    ,
    marginLeft
    , and
    marginTop
    . External CSS on the canvas will conflict.
  4. Fullscreen requires
    pointerup
    , not
    pointerdown
    .
    On touch devices,
    pointerdown
    fullscreen requests are blocked unless the document already received touch input. Always use
    pointerup
    for reliable behavior.
  5. Fullscreen in iframes needs
    allowfullscreen
    .
    Without this attribute on the iframe element, fullscreen requests will silently fail.
  6. RESIZE mode and GPU fill-rate. RESIZE creates a 1:1 pixel canvas matching the parent. On high-resolution displays this can be very large. Monitor performance on low-end devices.
  7. resize()
    vs
    setGameSize()
    .
    Use
    resize()
    only in NONE mode (it sets everything directly). Use
    setGameSize()
    when using FIT/ENVELOP/etc. (it preserves the scale mode calculations).
  8. iOS height quirks. When the parent is the window on iOS, the ScaleManager uses
    GetInnerHeight
    to work around Safari's dynamic toolbar affecting
    getBoundingClientRect
    .
  9. Percentage strings require a sized parent. Setting
    width: '100%'
    or
    height: '100%'
    resolves against
    parentSize
    . If the parent has no size, it falls back to
    window.innerWidth
    /
    innerHeight
    .
  10. resizeInterval
    is a fallback poll.
    Modern browsers dispatch
    resize
    events, but the ScaleManager also polls every
    resizeInterval
    ms (default 500) to catch edge cases on older browsers.
  1. 父元素必须有尺寸:ScaleManager依赖父容器的计算后CSS尺寸,未设置样式的
    <div>
    高度为0,会破坏居中与缩放效果。可以给父元素设置明确的CSS尺寸,或让默认的
    expandParent: true
    将body/父容器高度设为100%。
  2. 父元素不要加内边距:ScaleManager不会考虑父元素的内边距,可将内边距应用到包装元素,或在父元素的父元素上使用外边距。
  3. 不要直接设置canvas样式:ScaleManager会控制
    canvas.style.width
    canvas.style.height
    marginLeft
    marginTop
    ,外部对canvas的CSS设置会产生冲突。
  4. 全屏需要
    pointerup
    而非
    pointerdown
    :在触摸设备上,
    pointerdown
    触发的全屏请求会被拦截,除非文档已接收过触摸输入,始终使用
    pointerup
    才能保证可靠运行。
  5. iframe中的全屏需要
    allowfullscreen
    属性
    :如果iframe没有该属性,全屏请求会静默失败。
  6. RESIZE模式与GPU填充率:RESIZE会创建与父容器1:1像素匹配的canvas,在高分辨率显示器上尺寸可能很大,需关注低性能设备的运行表现。
  7. resize()
    setGameSize()
    的区别
    :仅在NONE模式下使用
    resize()
    (直接设置所有尺寸),在FIT/ENVELOP等模式下使用
    setGameSize()
    (保留缩放模式计算逻辑)。
  8. iOS高度问题:当父容器是iOS设备的窗口时,ScaleManager会使用
    GetInnerHeight
    来规避Safari动态工具栏影响
    getBoundingClientRect
    的问题。
  9. 百分比字符串需要父容器有尺寸:设置
    width: '100%'
    height: '100%'
    会根据
    parentSize
    解析,如果父容器没有尺寸,会回退到
    window.innerWidth
    /
    innerHeight
  10. resizeInterval
    是备用轮询机制
    :现代浏览器会触发
    resize
    事件,但ScaleManager仍会每隔
    resizeInterval
    毫秒(默认500)轮询一次,以兼容旧浏览器的边缘情况。

Source File Map

源码文件映射

FilePurpose
src/scale/ScaleManager.js
Main class -- all scaling, centering, fullscreen, orientation logic. Access via
game.scale
.
src/scale/const/SCALE_MODE_CONST.js
Scale mode constants: NONE, WIDTH_CONTROLS_HEIGHT, HEIGHT_CONTROLS_WIDTH, FIT, ENVELOP, RESIZE, EXPAND.
src/scale/const/CENTER_CONST.js
Center mode constants: NO_CENTER, CENTER_BOTH, CENTER_HORIZONTALLY, CENTER_VERTICALLY.
src/scale/const/ZOOM_CONST.js
Zoom constants: NO_ZOOM, ZOOM_2X, ZOOM_4X, MAX_ZOOM.
src/scale/const/ORIENTATION_CONST.js
Orientation string constants: LANDSCAPE, LANDSCAPE_SECONDARY, PORTRAIT, PORTRAIT_SECONDARY.
src/scale/events/RESIZE_EVENT.js
Resize event definition. Callback receives gameSize, baseSize, displaySize, previousWidth, previousHeight.
src/scale/events/ENTER_FULLSCREEN_EVENT.js
Emitted on successful fullscreen entry.
src/scale/events/LEAVE_FULLSCREEN_EVENT.js
Emitted when leaving fullscreen.
src/scale/events/FULLSCREEN_FAILED_EVENT.js
Emitted when fullscreen request is denied.
src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js
Emitted when browser lacks Fullscreen API support.
src/scale/events/ORIENTATION_CHANGE_EVENT.js
Emitted on device orientation change. Callback receives orientation string.
src/core/typedefs/ScaleConfig.js
JSDoc typedef for the
scale
config object.
src/structs/Size.js
The Size component class used by gameSize, baseSize, displaySize.
src/dom/GetInnerHeight.js
iOS-specific workaround for getting accurate viewport height.
src/dom/GetScreenOrientation.js
Determines current screen orientation from dimensions.
文件用途
src/scale/ScaleManager.js
主类——包含所有缩放、居中、全屏、方向逻辑,可通过
game.scale
访问。
src/scale/const/SCALE_MODE_CONST.js
缩放模式常量:NONE、WIDTH_CONTROLS_HEIGHT、HEIGHT_CONTROLS_WIDTH、FIT、ENVELOP、RESIZE、EXPAND。
src/scale/const/CENTER_CONST.js
居中模式常量:NO_CENTER、CENTER_BOTH、CENTER_HORIZONTALLY、CENTER_VERTICALLY。
src/scale/const/ZOOM_CONST.js
缩放常量:NO_ZOOM、ZOOM_2X、ZOOM_4X、MAX_ZOOM。
src/scale/const/ORIENTATION_CONST.js
方向字符串常量:LANDSCAPE、LANDSCAPE_SECONDARY、PORTRAIT、PORTRAIT_SECONDARY。
src/scale/events/RESIZE_EVENT.js
窗口调整事件定义,回调接收gameSize、baseSize、displaySize、previousWidth、previousHeight。
src/scale/events/ENTER_FULLSCREEN_EVENT.js
成功进入全屏时触发。
src/scale/events/LEAVE_FULLSCREEN_EVENT.js
退出全屏时触发。
src/scale/events/FULLSCREEN_FAILED_EVENT.js
全屏请求被拒绝时触发。
src/scale/events/FULLSCREEN_UNSUPPORTED_EVENT.js
浏览器不支持全屏API时触发。
src/scale/events/ORIENTATION_CHANGE_EVENT.js
设备方向变化时触发,回调接收方向字符串。
src/core/typedefs/ScaleConfig.js
scale
配置对象的JSDoc类型定义。
src/structs/Size.js
gameSize、baseSize、displaySize使用的Size组件类。
src/dom/GetInnerHeight.js
iOS专用的获取准确视口高度的解决方案。
src/dom/GetScreenOrientation.js
根据尺寸判断当前屏幕方向。