text-and-bitmaptext
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseText and BitmapText
Text与BitmapText
Displaying text in Phaser 4 -- the Canvas-based Text game object, TextStyle configuration, word wrap, BitmapText (static and dynamic), retro fonts, text alignment, text bounds, and padding.
Key source paths: , ,
Related skills: ../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md, ../game-object-components/SKILL.md
src/gameobjects/text/src/gameobjects/bitmaptext/static/src/gameobjects/bitmaptext/dynamic/在Phaser 4中显示文本——基于Canvas的Text游戏对象、TextStyle配置、自动换行、BitmapText(静态与动态)、复古字体、文本对齐、文本边界和内边距。
核心源码路径: , ,
相关技能: ../loading-assets/SKILL.md, ../sprites-and-images/SKILL.md, ../game-object-components/SKILL.md
src/gameobjects/text/src/gameobjects/bitmaptext/static/src/gameobjects/bitmaptext/dynamic/Quick Start
快速开始
js
// Canvas-based Text (flexible styling, uses browser fonts)
const title = this.add.text(400, 50, 'Hello World', {
fontFamily: 'Arial',
fontSize: '32px',
color: '#ffffff'
});
// BitmapText (pre-rendered font texture, faster rendering)
// Font must be loaded first: this.load.bitmapFont('myFont', 'font.png', 'font.xml')
const score = this.add.bitmapText(400, 100, 'myFont', 'Score: 0', 32);
// DynamicBitmapText (per-character manipulation via callback)
const fancy = this.add.dynamicBitmapText(400, 200, 'myFont', 'Wavy!', 32);
fancy.setDisplayCallback(function (data) {
data.y += Math.sin(data.index * 0.5 + fancy.scene.time.now * 0.005) * 10;
return data;
});js
// 基于Canvas的Text(样式灵活,使用浏览器字体)
const title = this.add.text(400, 50, 'Hello World', {
fontFamily: 'Arial',
fontSize: '32px',
color: '#ffffff'
});
// BitmapText(预渲染字体纹理,渲染速度更快)
// 必须先加载字体:this.load.bitmapFont('myFont', 'font.png', 'font.xml')
const score = this.add.bitmapText(400, 100, 'myFont', 'Score: 0', 32);
// DynamicBitmapText(通过回调实现逐字符操作)
const fancy = this.add.dynamicBitmapText(400, 200, 'myFont', 'Wavy!', 32);
fancy.setDisplayCallback(function (data) {
data.y += Math.sin(data.index * 0.5 + fancy.scene.time.now * 0.005) * 10;
return data;
});Core Concepts
核心概念
Text vs BitmapText
Text与BitmapText对比
| Feature | Text | BitmapText | DynamicBitmapText |
|---|---|---|---|
| Rendering method | Canvas 2D API, uploaded as texture | Pre-rendered font texture | Pre-rendered font texture |
| Web/CSS fonts | Yes | No | No |
| Shadows, gradients, strokes | Yes (Canvas API) | Drop shadow only (WebGL) | No |
| Word wrap | Built-in (width, callback, advanced) | | |
| Per-character effects | No | | |
| Performance | Slower (re-creates canvas texture on change) | Fast (batched rendering) | Moderate (callback per char) |
| Alignment | | | Same as BitmapText |
| RTL support | Yes ( | No | No |
Rule of thumb: Use for UI elements that need flexible styling, web fonts, or infrequent updates. Use for scores, timers, and anything that updates frequently or is rendered in large quantities. Use only when you need per-character animation effects.
TextBitmapTextDynamicBitmapText| 特性 | Text | BitmapText | DynamicBitmapText |
|---|---|---|---|
| 渲染方式 | Canvas 2D API,上传为纹理 | 预渲染字体纹理 | 预渲染字体纹理 |
| 支持Web/CSS字体 | 是 | 否 | 否 |
| 阴影、渐变、描边 | 是(基于Canvas API) | 仅支持投影(WebGL环境) | 否 |
| 自动换行 | 内置支持(按宽度、回调、高级模式) | | |
| 逐字符效果 | 否 | | |
| 性能表现 | 较慢(修改时重新创建Canvas纹理) | 快(批量渲染) | 中等(每个字符触发一次回调) |
| 对齐方式 | | | 与BitmapText一致 |
| 支持RTL(从右到左) | 是( | 否 | 否 |
经验法则: 需要灵活样式、Web字体或不频繁更新的UI元素,使用;分数、计时器等频繁更新或大量渲染的内容,使用;仅当需要逐字符动画效果时,才使用。
TextBitmapTextDynamicBitmapTextTextStyle
TextStyle
The game object delegates all styling to its instance, accessible via . You pass a style config object when creating the Text, or update it later with setter methods. The style object uses Canvas 2D properties internally.
TextTextStyletext.styleThe default is , default is , and default is . The shorthand property (e.g. ) overrides , , and when provided.
fontFamily'Courier'fontSize'16px'color'#fff'font'bold 24px Arial'fontFamilyfontSizefontStyleText游戏对象的所有样式都由其实例管理,可通过访问。创建Text时可传入样式配置对象,也可后续通过setter方法更新。样式对象内部使用Canvas 2D属性。
TextStyletext.stylefontFamily'Courier'fontSize'16px'color'#fff'font'bold 24px Arial'fontFamilyfontSizefontStyleCommon Patterns
常见用法
Basic Text Creation
基础文本创建
js
// Simple text with inline style
const label = this.add.text(100, 100, 'Player 1', {
fontFamily: 'Georgia',
fontSize: '24px',
color: '#00ff00'
});
// Using the font shorthand (sets fontStyle, fontSize, fontFamily)
const bold = this.add.text(100, 150, 'Bold Text', {
font: 'bold 28px Arial'
});
// Array of strings creates multi-line text
const multi = this.add.text(100, 200, ['Line 1', 'Line 2', 'Line 3'], {
fontFamily: 'Arial',
fontSize: '18px',
color: '#ffffff'
});
// Text origin defaults to (0, 0) -- top-left corner
label.setOrigin(0.5); // center the text on its positionjs
// 带内联样式的简单文本
const label = this.add.text(100, 100, 'Player 1', {
fontFamily: 'Georgia',
fontSize: '24px',
color: '#00ff00'
});
// 使用font简写(同时设置fontStyle、fontSize、fontFamily)
const bold = this.add.text(100, 150, 'Bold Text', {
font: 'bold 28px Arial'
});
// 字符串数组会创建多行文本
const multi = this.add.text(100, 200, ['Line 1', 'Line 2', 'Line 3'], {
fontFamily: 'Arial',
fontSize: '18px',
color: '#ffffff'
});
// Text原点默认为(0, 0)——左上角
label.setOrigin(0.5); // 将文本居中定位Styling Text
文本样式设置
js
const text = this.add.text(400, 300, 'Styled', {
fontFamily: 'Verdana',
fontSize: '48px',
color: '#ff0000',
stroke: '#000000',
strokeThickness: 4,
backgroundColor: '#333333',
shadow: { offsetX: 2, offsetY: 2, color: '#000', blur: 4, stroke: false, fill: true }
});
// Modify style after creation (all return `this` for chaining)
text.setColor('#00ffff');
text.setFontSize(64);
text.setFontFamily('Courier');
text.setFontStyle('italic');
text.setStroke('#ff00ff', 6);
text.setShadow(3, 3, '#000', 5, false, true);
text.setBackgroundColor('#222');
// Replace entire style at once
text.setStyle({ fontSize: '64px', fontFamily: 'Arial', color: '#ffffff', align: 'center' });
// Canvas gradients and patterns work as fill/stroke
const gradient = text.context.createLinearGradient(0, 0, 0, text.height);
gradient.addColorStop(0, '#ff0000');
gradient.addColorStop(1, '#0000ff');
text.setFill(gradient);js
const text = this.add.text(400, 300, 'Styled', {
fontFamily: 'Verdana',
fontSize: '48px',
color: '#ff0000',
stroke: '#000000',
strokeThickness: 4,
backgroundColor: '#333333',
shadow: { offsetX: 2, offsetY: 2, color: '#000', blur: 4, stroke: false, fill: true }
});
// 创建后修改样式(所有方法均返回`this`以支持链式调用)
text.setColor('#00ffff');
text.setFontSize(64);
text.setFontFamily('Courier');
text.setFontStyle('italic');
text.setStroke('#ff00ff', 6);
text.setShadow(3, 3, '#000', 5, false, true);
text.setBackgroundColor('#222');
// 一次性替换整个样式
text.setStyle({ fontSize: '64px', fontFamily: 'Arial', color: '#ffffff', align: 'center' });
// Canvas渐变和图案可作为填充/描边
const gradient = text.context.createLinearGradient(0, 0, 0, text.height);
gradient.addColorStop(0, '#ff0000');
gradient.addColorStop(1, '#0000ff');
text.setFill(gradient);Word Wrap
自动换行
js
// Basic word wrap by pixel width
const wrapped = this.add.text(50, 50, 'Long text here...', {
fontFamily: 'Arial',
fontSize: '20px',
color: '#fff',
wordWrap: { width: 300 }
});
// Or set after creation
wrapped.setWordWrapWidth(300);
// Advanced wrap (collapses spaces, trims whitespace)
wrapped.setWordWrapWidth(300, true);
// Custom word wrap callback
wrapped.setWordWrapCallback(function (text, textObject) {
// Return wrapped text as string with \n or array of lines
return text.split(' ').join('\n');
});
// Get wrapped lines as array
const lines = wrapped.getWrappedText();js
// 基于像素宽度的基础自动换行
const wrapped = this.add.text(50, 50, 'Long text here...', {
fontFamily: 'Arial',
fontSize: '20px',
color: '#fff',
wordWrap: { width: 300 }
});
// 也可在创建后设置
wrapped.setWordWrapWidth(300);
// 高级换行(合并空格、修剪空白符)
wrapped.setWordWrapWidth(300, true);
// 自定义自动换行回调
wrapped.setWordWrapCallback(function (text, textObject) {
// 返回带\n的字符串或行数组作为换行结果
return text.split(' ').join('\n');
});
// 获取换行后的行数组
const lines = wrapped.getWrappedText();Text Alignment
文本对齐
js
// Alignment only affects multi-line text: 'left' (default), 'right', 'center', 'justify'
const aligned = this.add.text(400, 100, 'Line 1\nLonger Line 2\nLine 3', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff', align: 'center'
});
aligned.setAlign('right');
// For center alignment to look correct, combine with fixedWidth:
aligned.setFixedSize(300, 0);
aligned.setAlign('center');js
// 对齐仅对多行文本生效:'left'(默认)、'right'、'center'、'justify'
const aligned = this.add.text(400, 100, 'Line 1\nLonger Line 2\nLine 3', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff', align: 'center'
});
aligned.setAlign('right');
// 要使居中对齐显示正确,需配合fixedWidth使用:
aligned.setFixedSize(300, 0);
aligned.setAlign('center');Dynamic Text Updates
动态文本更新
js
const scoreText = this.add.text(10, 10, 'Score: 0', {
fontFamily: 'Arial',
fontSize: '24px',
color: '#fff'
});
// setText replaces content (accepts string or string[])
scoreText.setText('Score: 100');
scoreText.setText(['Score: 100', 'Lives: 3']); // joins with \n
// appendText adds to existing content
scoreText.appendText('Extra line'); // prepends \n by default
scoreText.appendText(' more', false); // no carriage return
// Read current text
const current = scoreText.text;js
const scoreText = this.add.text(10, 10, 'Score: 0', {
fontFamily: 'Arial',
fontSize: '24px',
color: '#fff'
});
// setText替换内容(接受字符串或字符串数组)
scoreText.setText('Score: 100');
scoreText.setText(['Score: 100', 'Lives: 3']); // 用\n连接
// appendText向现有内容追加文本
scoreText.appendText('Extra line'); // 默认前置\n
scoreText.appendText(' more', false); // 不添加换行符
// 读取当前文本内容
const current = scoreText.text;Text Padding
文本内边距
js
// Padding adds space around text inside the canvas
const padded = this.add.text(100, 100, 'Padded', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff',
backgroundColor: '#333',
padding: { left: 10, right: 10, top: 5, bottom: 5 }
});
padded.setPadding({ x: 10, y: 5 }); // shorthand: x=left+right, y=top+bottom
padded.setPadding(10, 5, 10, 5); // left, top, right, bottom
padded.setPadding(10); // single value = all sidesjs
// 内边距会在Canvas内为文本添加周围空间
const padded = this.add.text(100, 100, 'Padded', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff',
backgroundColor: '#333',
padding: { left: 10, right: 10, top: 5, bottom: 5 }
});
padded.setPadding({ x: 10, y: 5 }); // 简写:x=左+右,y=上+下
padded.setPadding(10, 5, 10, 5); // 左、上、右、下
padded.setPadding(10); // 单个值表示所有边Fixed Size, Max Lines, and Spacing
固定尺寸、最大行数与间距
js
// Fixed dimensions create a text canvas of exact size
const fixed = this.add.text(100, 100, 'Fixed box', {
fontFamily: 'Arial', fontSize: '18px', color: '#fff',
fixedWidth: 200, fixedHeight: 100,
wordWrap: { width: 200 }, align: 'center'
});
fixed.setMaxLines(3); // limit displayed lines
// Line and letter spacing (in style config or via setters)
const spaced = this.add.text(100, 200, 'Spaced\nLines', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff',
lineSpacing: 10, letterSpacing: 2
});
spaced.setLineSpacing(20);
spaced.setLetterSpacing(5);js
// 固定尺寸会创建精确大小的文本Canvas
const fixed = this.add.text(100, 100, 'Fixed box', {
fontFamily: 'Arial', fontSize: '18px', color: '#fff',
fixedWidth: 200, fixedHeight: 100,
wordWrap: { width: 200 }, align: 'center'
});
fixed.setMaxLines(3); // 限制显示行数
// 行间距与字符间距(可在样式配置或通过setter设置)
const spaced = this.add.text(100, 200, 'Spaced\nLines', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff',
lineSpacing: 10, letterSpacing: 2
});
spaced.setLineSpacing(20);
spaced.setLetterSpacing(5);BitmapText Creation
BitmapText创建
js
// Load in preload: this.load.bitmapFont('pixelFont', 'font.png', 'font.xml');
// Static BitmapText -- fast, batched rendering
const bmpText = this.add.bitmapText(100, 100, 'pixelFont', 'Hello', 32);
// With alignment (for multi-line)
const aligned = this.add.bitmapText(100, 200, 'pixelFont', 'Line 1\nLine 2', 24, 1);
// align: 0 = left, 1 = center, 2 = right
// Convenience alignment methods
bmpText.setLeftAlign();
bmpText.setCenterAlign();
bmpText.setRightAlign();
// Modify text
bmpText.setText('Updated!');
bmpText.text = 'Also works';
// Font size
bmpText.setFontSize(48);
bmpText.fontSize = 48;
// Spacing
bmpText.setLetterSpacing(2);
bmpText.setLineSpacing(5);
// Word wrap by max pixel width
bmpText.setMaxWidth(200);js
// 在preload中加载:this.load.bitmapFont('pixelFont', 'font.png', 'font.xml');
// 静态BitmapText——快速批量渲染
const bmpText = this.add.bitmapText(100, 100, 'pixelFont', 'Hello', 32);
// 带对齐的多行文本
const aligned = this.add.bitmapText(100, 200, 'pixelFont', 'Line 1\nLine 2', 24, 1);
// align: 0 = 左对齐, 1 = 居中, 2 = 右对齐
// 便捷对齐方法
bmpText.setLeftAlign();
bmpText.setCenterAlign();
bmpText.setRightAlign();
// 修改文本内容
bmpText.setText('Updated!');
bmpText.text = 'Also works';
// 字体大小
bmpText.setFontSize(48);
bmpText.fontSize = 48;
// 间距设置
bmpText.setLetterSpacing(2);
bmpText.setLineSpacing(5);
// 基于最大像素宽度自动换行
bmpText.setMaxWidth(200);BitmapText Drop Shadow and Tinting
BitmapText投影与着色
js
// Drop shadow (WebGL only, static BitmapText only)
bmpText.setDropShadow(2, 2, 0x000000, 0.5);
// Clear shadow
bmpText.setDropShadow();
// Tint individual characters (WebGL only)
bmpText.setCharacterTint(0, 5, Phaser.TintModes.MULTIPLY, 0xff0000);
// start index, length (-1 for all from start), tintMode, color
// Tint by word (string match or word index)
bmpText.setWordTint('Score', -1, Phaser.TintModes.MULTIPLY, 0x00ff00);js
// 投影(仅WebGL环境、仅静态BitmapText支持)
bmpText.setDropShadow(2, 2, 0x000000, 0.5);
// 清除投影
bmpText.setDropShadow();
// 逐字符着色(仅WebGL环境)
bmpText.setCharacterTint(0, 5, Phaser.TintModes.MULTIPLY, 0xff0000);
// 参数:起始索引、长度(-1表示从起始到末尾)、着色模式、颜色
// 按单词着色(匹配字符串或单词索引)
bmpText.setWordTint('Score', -1, Phaser.TintModes.MULTIPLY, 0x00ff00);DynamicBitmapText
DynamicBitmapText
js
const dynamic = this.add.dynamicBitmapText(100, 100, 'pixelFont', 'Dynamic!', 32);
// Per-character display callback -- invoked each render frame per character
dynamic.setDisplayCallback(function (data) {
// data properties: parent, tint, index, charCode, x, y, scale, rotation, data
data.x += Math.sin(data.index + dynamic.scene.time.now * 0.01) * 5;
data.y += Math.cos(data.index + dynamic.scene.time.now * 0.01) * 5;
return data;
});
// Scrolling text window
dynamic.setSize(200, 50); // crop region in pixels
dynamic.setScrollX(10);
dynamic.setScrollY(0);js
const dynamic = this.add.dynamicBitmapText(100, 100, 'pixelFont', 'Dynamic!', 32);
// 逐字符显示回调——每帧渲染时对每个字符调用一次
dynamic.setDisplayCallback(function (data) {
// data属性:parent、tint、index、charCode、x、y、scale、rotation、data
data.x += Math.sin(data.index + dynamic.scene.time.now * 0.01) * 5;
data.y += Math.cos(data.index + dynamic.scene.time.now * 0.01) * 5;
return data;
});
// 滚动文本窗口
dynamic.setSize(200, 50); // 裁剪区域(像素单位)
dynamic.setScrollX(10);
dynamic.setScrollY(0);Retro Fonts
复古字体
Retro fonts use a fixed-width character grid from a standard image (no XML/JSON font file needed).
js
// In preload -- load the image containing the font characters
this.load.image('retroFont', 'retroFont.png');
// In create -- parse the retro font configuration
const config = {
image: 'retroFont',
width: 8, // character width in pixels
height: 8, // character height in pixels
chars: Phaser.GameObjects.RetroFont.TEXT_SET1,
charsPerRow: 16,
offset: { x: 0, y: 0 },
spacing: { x: 0, y: 0 },
lineSpacing: 0
};
// Parse adds it to the BitmapFont cache
this.cache.bitmapFont.add('retroFont', { data: Phaser.GameObjects.RetroFont.Parse(this, config) });
// Now use it like any BitmapText
const retro = this.add.bitmapText(100, 100, 'retroFont', 'RETRO TEXT', 8);Available TEXT_SET constants: (full ASCII printable), (space through Z), - (various subsets of uppercase, digits, punctuation). is uppercase letters only.
Phaser.GameObjects.RetroFontTEXT_SET1TEXT_SET2TEXT_SET3TEXT_SET11TEXT_SET10复古字体使用标准图片中的固定宽度字符网格,无需XML/JSON字体文件。
js
// 在preload中加载包含字体字符的图片
this.load.image('retroFont', 'retroFont.png');
// 在create中解析复古字体配置
const config = {
image: 'retroFont',
width: 8, // 字符宽度(像素)
height: 8, // 字符高度(像素)
chars: Phaser.GameObjects.RetroFont.TEXT_SET1,
charsPerRow: 16,
offset: { x: 0, y: 0 },
spacing: { x: 0, y: 0 },
lineSpacing: 0
};
// 解析后添加到BitmapFont缓存
this.cache.bitmapFont.add('retroFont', { data: Phaser.GameObjects.RetroFont.Parse(this, config) });
// 现在可像普通BitmapText一样使用
const retro = this.add.bitmapText(100, 100, 'retroFont', 'RETRO TEXT', 8);可用的 TEXT_SET常量:(完整可打印ASCII字符)、(空格到Z)、-(大写字母、数字、标点的各种子集)。仅包含大写字母。
Phaser.GameObjects.RetroFontTEXT_SET1TEXT_SET2TEXT_SET3TEXT_SET11TEXT_SET10Text Bounds (BitmapText)
文本边界(BitmapText)
js
// getTextBounds returns local, global, line, word, and character data
const bounds = bmpText.getTextBounds();
// bounds.local -- { x, y, width, height } at origin 0,0
// bounds.global -- { x, y, width, height } with scale + world position
// bounds.lines -- per-line { x, y, width, height }
// bounds.words -- word objects with positions
// bounds.characters -- character objects with positions
// width/height are read-only properties (computed from global bounds)
console.log(bmpText.width, bmpText.height);
// Get character at world position (useful for click detection)
const char = bmpText.getCharacterAt(pointer.worldX, pointer.worldY);js
// getTextBounds返回本地、全局、行、单词和字符数据
const bounds = bmpText.getTextBounds();
// bounds.local -- 原点(0,0)处的{x, y, width, height}
// bounds.global -- 包含缩放和世界位置的{x, y, width, height}
// bounds.lines -- 每行的{x, y, width, height}
// bounds.words -- 带位置信息的单词对象
// bounds.characters -- 带位置信息的字符对象
// width/height为只读属性(由全局边界计算得出)
console.log(bmpText.width, bmpText.height);
// 获取世界位置对应的字符(适用于点击检测)
const char = bmpText.getCharacterAt(pointer.worldX, pointer.worldY);Resolution (High DPI)
分辨率(高DPI)
js
// Higher resolution for crisp text on HiDPI displays (costs more memory)
const crisp = this.add.text(100, 100, 'Sharp!', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff', resolution: 2
});
crisp.setResolution(window.devicePixelRatio); // change after creationjs
// 更高分辨率可在高DPI显示器上显示清晰文本(占用更多内存)
const crisp = this.add.text(100, 100, 'Sharp!', {
fontFamily: 'Arial', fontSize: '24px', color: '#fff', resolution: 2
});
crisp.setResolution(window.devicePixelRatio); // 创建后修改分辨率Configuration Reference
配置参考
TextStyle Properties
TextStyle属性
| Property | Type | Default | Description |
|---|---|---|---|
| string | | CSS font family |
| string/number | | Font size (number auto-appends |
| string | | CSS font style ( |
| string | - | Shorthand: |
| string/CanvasGradient/CanvasPattern | | Fill color |
| string/CanvasGradient/CanvasPattern | | Stroke color |
| number | | Stroke width (0 = no stroke) |
| string | | Solid background color |
| string | | Multi-line alignment: |
| number | | Max lines to render (0 = unlimited) |
| number | | Fixed canvas width (0 = auto) |
| number | | Fixed canvas height (0 = auto) |
| number | | Canvas resolution (0 = use game config) |
| boolean | | Right-to-left rendering |
| number | | Horizontal padding for font metrics |
| number | | Vertical padding for font metrics |
| string | | String used for font height measurement |
| object | - | |
| object | - | |
| object | - | |
| number | | Extra vertical spacing between lines |
| number | | Extra horizontal spacing between characters |
| object | - | Pre-computed |
| 属性 | 类型 | 默认值 | 描述 |
|---|---|---|---|
| string | | CSS字体族 |
| string/number | | 字体大小(数字会自动追加 |
| string | | CSS字体样式( |
| string | - | 简写形式: |
| string/CanvasGradient/CanvasPattern | | 填充颜色 |
| string/CanvasGradient/CanvasPattern | | 描边颜色 |
| number | | 描边宽度(0表示无描边) |
| string | | 纯色背景 |
| string | | 多行文本对齐: |
| number | | 最大渲染行数(0表示无限制) |
| number | | 固定Canvas宽度(0表示自动) |
| number | | 固定Canvas高度(0表示自动) |
| number | | Canvas分辨率(0表示使用游戏配置) |
| boolean | | 从右到左渲染 |
| number | | 字体度量的水平内边距 |
| number | | 字体度量的垂直内边距 |
| string | | 用于测量字体高度的字符串 |
| object | - | |
| object | - | |
| object | - | |
| number | | 行之间的额外垂直间距 |
| number | | 字符之间的额外水平间距 |
| object | - | 预计算的 |
Factory Methods
工厂方法
js
// Text -- Canvas-based
this.add.text(x, y, text, style);
// x, y: number; text: string | string[]; style: TextStyle (optional)
// Returns: Phaser.GameObjects.Text
// BitmapText -- static, fast
this.add.bitmapText(x, y, font, text, size, align);
// x, y: number; font: string (cache key); text: string | string[] (optional)
// size: number (optional, defaults to font data size); align: number (optional, 0)
// Returns: Phaser.GameObjects.BitmapText
// DynamicBitmapText -- per-character callback
this.add.dynamicBitmapText(x, y, font, text, size);
// Same as bitmapText but returns DynamicBitmapText
// Returns: Phaser.GameObjects.DynamicBitmapTextjs
// Text——基于Canvas
this.add.text(x, y, text, style);
// x, y: 数字; text: 字符串 | 字符串数组; style: TextStyle(可选)
// 返回值: Phaser.GameObjects.Text
// BitmapText——静态、快速
this.add.bitmapText(x, y, font, text, size, align);
// x, y: 数字; font: 字符串(缓存键); text: 字符串 | 字符串数组(可选)
// size: 数字(可选,默认使用字体数据大小); align: 数字(可选,默认0)
// 返回值: Phaser.GameObjects.BitmapText
// DynamicBitmapText——逐字符回调
this.add.dynamicBitmapText(x, y, font, text, size);
// 参数与bitmapText相同,但返回DynamicBitmapText
// 返回值: Phaser.GameObjects.DynamicBitmapTextAPI Quick Reference
API快速参考
Text Methods
Text方法
setText(value)appendText(value, addCR?)setStyle(style)setFont(font)setFontFamily(family)setFontSize(size)setFontStyle(style)setColor(color)setFill(color)setStroke(color, thickness)setShadow(x, y, color, blur, stroke, fill)setBackgroundColor(color)setWordWrapWidth(width, useAdvanced?)setWordWrapCallback(callback, scope?)setAlign(align)setPadding(left, top?, right?, bottom?)setFixedSize(width, height)setMaxLines(max)setLineSpacing(value)setLetterSpacing(value)setResolution(value)setRTL(rtl?)getWrappedText(text?)updateText()All setters return for chaining. Properties: (get/set), (TextStyle instance), , , , , .
thistextstylepaddinglineSpacingletterSpacingautoRoundsplitRegExpsetText(value)appendText(value, addCR?)setStyle(style)setFont(font)setFontFamily(family)setFontSize(size)setFontStyle(style)setColor(color)setFill(color)setStroke(color, thickness)setShadow(x, y, color, blur, stroke, fill)setBackgroundColor(color)setWordWrapWidth(width, useAdvanced?)setWordWrapCallback(callback, scope?)setAlign(align)setPadding(left, top?, right?, bottom?)setFixedSize(width, height)setMaxLines(max)setLineSpacing(value)setLetterSpacing(value)setResolution(value)setRTL(rtl?)getWrappedText(text?)updateText()所有setter方法均返回以支持链式调用。属性:(可读写)、(TextStyle实例)、、、、、。
thistextstylepaddinglineSpacingletterSpacingautoRoundsplitRegExpBitmapText Methods
BitmapText方法
setText(value)setFont(font, size?, align?)setFontSize(size)setLetterSpacing(spacing?)setLineSpacing(spacing?)setMaxWidth(value, wordWrapCharCode?)setLeftAlign()setCenterAlign()setRightAlign()setDropShadow(x?, y?, color?, alpha?)setCharacterTint(start?, length?, tintMode?, tl?, tr?, bl?, br?)setWordTint(word, count?, tintMode?, tl?, tr?, bl?, br?)getTextBounds(round?)getCharacterAt(x, y, camera?)Properties (get/set): , , , , (number), . Read-only: , , , .
textfontSizeletterSpacinglineSpacingalignmaxWidthwidthheightfontfontDataAlignment constants: (0), (1), (2).
BitmapText.ALIGN_LEFTBitmapText.ALIGN_CENTERBitmapText.ALIGN_RIGHTsetText(value)setFont(font, size?, align?)setFontSize(size)setLetterSpacing(spacing?)setLineSpacing(spacing?)setMaxWidth(value, wordWrapCharCode?)setLeftAlign()setCenterAlign()setRightAlign()setDropShadow(x?, y?, color?, alpha?)setCharacterTint(start?, length?, tintMode?, tl?, tr?, bl?, br?)setWordTint(word, count?, tintMode?, tl?, tr?, bl?, br?)getTextBounds(round?)getCharacterAt(x, y, camera?)属性(可读写):、、、、(数字)、。只读属性:、、、。
textfontSizeletterSpacinglineSpacingalignmaxWidthwidthheightfontfontData对齐常量: (0)、 (1)、 (2)。
BitmapText.ALIGN_LEFTBitmapText.ALIGN_CENTERBitmapText.ALIGN_RIGHTDynamicBitmapText Methods (additional)
DynamicBitmapText额外方法
setDisplayCallback(callback)setSize(width, height)setScrollX(value)setScrollY(value)Properties: , , , , , .
scrollXscrollYcropWidthcropHeightdisplayCallbackcallbackDatasetDisplayCallback(callback)setSize(width, height)setScrollX(value)setScrollY(value)属性:、、、、、。
scrollXscrollYcropWidthcropHeightdisplayCallbackcallbackDataGotchas
注意事项
-
Text re-renders on every change. Each call to,
setText,setStyle, etc. re-creates the internal canvas and (in WebGL) re-uploads the texture. Batch your style changes and callsetColoronce, or set the style object properties directly and callupdateText()at the end.updateText() -
Font must be loaded before use. The Text object uses the CanvasAPI, so fonts must be available in the browser (loaded via CSS, a web font loader, or already installed). Phaser does not load web fonts -- use a third-party loader or CSS
fillText.@font-face -
Font names with special characters need quotes. Font names containing digits or special characters must be double-quoted inside the string:.
fontFamily: '"Press Start 2P"' -
Text origin defaults to (0, 0). Unlike Sprites which default to (0.5, 0.5), Text objects default to top-left origin. Callto center.
setOrigin(0.5) -
Alignment only affects multi-line text.does nothing on single-line text. For centering a single line, use
align: 'center'or position it manually.setOrigin(0.5) -
BitmapText font must be in cache. The font key passed tomust match a key loaded via
this.add.bitmapText(). If missing, you get a console warning and undefined behavior.this.load.bitmapFont() -
BitmapTextonly wraps on whitespace. If no whitespace character is found (default char code 32 = space), no wrapping occurs. Change the wrap character with the second argument to
setMaxWidth.setMaxWidth -
DynamicBitmapText is more expensive. The display callback runs for every character every frame. Only use it when you need per-character manipulation.
-
and
setCharacterTintare WebGL only. These have no effect in Canvas renderer.setWordTint -
is WebGL only and static BitmapText only. It does not work with DynamicBitmapText or the Canvas renderer.
setDropShadow -
on Text is expensive. When non-zero, Phaser renders each character individually with
letterSpacinginstead of the whole line at once. Use BitmapText for large amounts of text with custom letter spacing.fillText -
and
setFillare equivalent. Both set thesetColorproperty on the TextStyle. The style config also acceptscoloras an alias forfill.color -
must be called BEFORE
setRTL. Right-to-left mode changes how the internal canvas is constructed. If you callsetTextafter setting text, the text may not render correctly. Set RTL in the style config or callsetRTL(true)before anysetRTL()call.setText() -
BitmapText is much faster for frequently updating content. Text re-renders its entire Canvas and re-uploads the GPU texture on every change. BitmapText just updates vertex data in an existing texture atlas. For scores, timers, damage numbers, or any text that changes every frame, always prefer BitmapText.
-
每次修改都会重新渲染Text:调用、
setText、setStyle等方法时,都会重新创建内部Canvas并(在WebGL环境中)重新上传纹理。建议批量修改样式后调用一次setColor,或直接修改样式对象属性后调用updateText()。updateText() -
字体必须先加载再使用:Text对象使用CanvasAPI,因此字体必须在浏览器中可用(通过CSS、Web字体加载器加载,或已安装在系统中)。Phaser不提供Web字体加载功能——请使用第三方加载器或CSS
fillText。@font-face -
含特殊字符的字体名称需加引号:包含数字或特殊字符的字体名称,必须在字符串内添加双引号:。
fontFamily: '"Press Start 2P"' -
Text原点默认为(0, 0):与默认原点为(0.5, 0.5)的Sprite不同,Text对象默认原点为左上角。调用可将其居中。
setOrigin(0.5) -
对齐仅对多行文本生效:对单行文本无效。要居中单行文本,使用
align: 'center'或手动定位。setOrigin(0.5) -
BitmapText字体必须在缓存中:传递给的字体键必须与
this.add.bitmapText()加载的键匹配。如果缺失,会触发控制台警告并导致未定义行为。this.load.bitmapFont() -
BitmapText的仅在空白字符处换行:如果未找到空白字符(默认字符码32=空格),则不会换行。可通过
setMaxWidth的第二个参数修改换行字符。setMaxWidth -
DynamicBitmapText性能开销更高:显示回调会在每帧对每个字符执行一次。仅在需要逐字符操作时使用。
-
和
setCharacterTint仅支持WebGL:在Canvas渲染器中无效果。setWordTint -
仅支持WebGL和静态BitmapText:对DynamicBitmapText或Canvas渲染器无效。
setDropShadow -
Text的性能开销高:当值非零时,Phaser会使用
letterSpacing逐字符渲染,而非整行渲染。大量带自定义字符间距的文本建议使用BitmapText。fillText -
和
setFill功能等价:两者都会设置TextStyle的setColor属性。样式配置中也接受color作为fill的别名。color -
必须在
setRTL之前调用:从右到左模式会改变内部Canvas的构建方式。如果在设置文本后调用setText,文本可能无法正确渲染。建议在样式配置中设置RTL,或在任何setRTL(true)调用前调用setText()。setRTL() -
BitmapText对频繁更新的内容性能更优:Text每次修改都会重新渲染整个Canvas并重新上传GPU纹理;BitmapText仅更新现有纹理图集的顶点数据。分数、计时器、伤害数字等每帧变化的文本,始终优先使用BitmapText。
Source File Map
源码文件映射
| File | Description |
|---|---|
| Text class (Canvas-based rendering) |
| |
| TextStyle class (all style properties + setters) |
| Internal text measurement |
| Font metrics measurement |
| TextStyle, TextWordWrap, TextPadding, TextShadow typedefs |
| Static BitmapText class |
| |
| DynamicBitmapText (extends BitmapText) |
| |
| Retro font parser ( |
| RetroFont namespace (Parse + TEXT_SET constants) |
| TEXT_SET1 through TEXT_SET11 constants |
| BitmapText bounds calculation |
| RetroFontConfig, DisplayCallbackConfig, BitmapTextSize typedefs |
| 文件 | 描述 |
|---|---|
| Text类(基于Canvas渲染) |
| |
| TextStyle类(所有样式属性+setter) |
| 内部文本测量逻辑 |
| 字体度量测量逻辑 |
| TextStyle、TextWordWrap、TextPadding、TextShadow类型定义 |
| 静态BitmapText类 |
| |
| DynamicBitmapText(继承自BitmapText) |
| |
| 复古字体解析器( |
| RetroFont命名空间(Parse+TEXT_SET常量) |
| TEXT_SET1至TEXT_SET11常量 |
| BitmapText边界计算逻辑 |
| RetroFontConfig、DisplayCallbackConfig、BitmapTextSize类型定义 |