文本(画布)
¥Text (Canvas)
PixiJS 中的 Text
类允许你将样式化的动态字符串渲染为场景中的显示对象。在底层,PixiJS 使用浏览器的 Canvas 文本 API 对文本进行栅格化,然后将其转换为纹理。这使得 Text
对象的行为类似于精灵:它们可以高效地移动、旋转、缩放、遮罩和渲染。
¥The Text
class in PixiJS allows you to render styled, dynamic strings as display objects in your scene. Under the hood, PixiJS rasterizes the text using the browser’s canvas text API, then converts that into a texture. This makes Text
objects behave like sprites: they can be moved, rotated, scaled, masked, and rendered efficiently.
import { Text, TextStyle, Assets } from 'pixi.js';
// Load font before use
await Assets.load({
src: 'my-font.woff2',
data: {
family: 'MyFont', // optional
}
});
const myText = new Text({
text: 'Hello PixiJS!',
style: {
fill: '#ffffff',
fontSize: 36,
fontFamily: 'MyFont',
}
anchor: 0.5
});
app.stage.addChild(myText);
文本样式
¥Text Styling
TextStyle
类允许你自定义文本的外观。你可以设置以下属性:
¥The TextStyle
class allows you to customize the appearance of your text. You can set properties like:
-
fontFamily
-
fontSize
-
fontWeight
-
fill
(颜色)¥
fill
(color) -
align
-
stroke
(轮廓)¥
stroke
(outline)
更多详情,请参阅 TextStyle 指南。
¥See the guide on TextStyle for more details.
动态更改文本
¥Changing Text Dynamically
你可以在运行时更新文本字符串或其样式:
¥You can update the text string or its style at runtime:
text.text = 'Updated!';
text.style.fontSize = 40; // Triggers re-render
更改文本或样式会重新栅格化对象。除非必要,否则请避免每帧都执行此操作。
¥Changing text or style re-rasterizes the object. Avoid doing this every frame unless necessary.
文本分辨率
¥Text Resolution
Text
类的 resolution
属性决定了渲染文本的像素密度。默认情况下,它使用渲染器的分辨率。
¥The resolution
property of the Text
class determines the pixel density of the rendered text. By default, it uses the resolution of the renderer.
但是,你可以独立于渲染器设置文本分辨率,以获得更清晰的文本,尤其是在高 DPI 显示屏上。
¥However, you can set text resolution independently from the renderer for sharper text, especially on high-DPI displays.
const myText = new Text('Hello', {
resolution: 2, // Higher resolution for sharper text
});
// change resolution
myText.resolution = 1; // Reset to default
字体加载
¥Font Loading
PixiJS 支持通过 Assets
API 加载自定义字体。它支持多种常见的字体格式:
¥PixiJS supports loading custom fonts via the Assets
API. It supports many of the common font formats:
-
woff
-
woff2
-
ttf
-
otf
建议使用 woff2
以获得最佳性能和压缩率。
¥It is recommended to use woff2
for the best performance and compression.
await Assets.load({
src: 'my-font.woff2',
data: {}
});
以下是加载字体时可以传入 data
对象的属性列表:
¥Below is a list of properties you can pass in the data
object when loading a font:
属性 | 描述 |
---|---|
family | 字体系列名称。 |
display | FontFace 接口的 display 属性。 |
featureSettings | FontFace 接口的 featureSettings 属性。 |
stretch | FontFace 接口的 stretch 属性。 |
style | FontFace 接口的 style 属性。 |
unicodeRange | FontFace 接口的 unicodeRange 属性。 |
variant | FontFace 接口的 variant 属性。 |
weights | FontFace 接口的 weights 属性。 |
API 参考
¥API Reference