HTML 文本
🌐 HTML Text
HTMLText 允许将带样式、格式化的 HTML 字符串作为 PixiJS 场景图的一部分进行渲染。它使用 SVG <foreignObject> 在你的 WebGL 画布中嵌入浏览器原生的 HTML。
这使得它非常适合渲染复杂的字体、内联格式、表情符号和布局效果,而这些效果是传统画布渲染文本难以复制的。
🌐 This makes it ideal for rendering complex typography, inline formatting, emojis, and layout effects that are hard to replicate using traditional canvas-rendered text.
import { HTMLText } from 'pixi.js';
const html = new HTMLText({
text: '<strong>Hello</strong> <em>PixiJS</em>!',
style: {
fontFamily: 'Arial',
fontSize: 24,
fill: '#ff1010',
align: 'center',
},
});
app.stage.addChild(html);
为什么使用 HTMLText?
🌐 Why Use HTMLText?
- ✅ 支持像
<b>、<i>、<span>等内联标签。 - ✅ 兼容表情符号、Unicode 和从右到左文本
- ✅ 通过 CSS 进行精细布局控制
- ✅ 基于标签的样式覆盖(
<warning>、<link>等)
异步渲染行为
🌐 Async Rendering Behavior
HTML 文本使用 SVG <foreignObject> 在画布内绘制 HTML。因此:
🌐 HTML text uses SVG <foreignObject> to draw HTML inside the canvas. As a result:
- 渲染是异步进行的。通常在下一帧之后。
- 文本内容在实例化后不会立即显示。
为HTML文本设定样式
🌐 Styling HTMLText
HTMLTextStyle 继承自 TextStyle 并添加了:
- 支持 HTML 的基于标签的样式 通过
tagStyles - 通过
cssOverrides支持 CSS 覆盖
const fancy = new HTMLText({
text: '<red>Red</red>, <blue>Blue</blue>',
style: {
fontFamily: 'DM Sans',
fontSize: 32,
fill: '#ffffff',
tagStyles: {
red: { fill: 'red' },
blue: { fill: 'blue' },
},
},
});
CSS 覆盖
🌐 CSS Overrides
你可以使用 cssOverrides 属性对文本应用 CSS 样式。这允许你设置像 text-shadow、text-decoration 等属性。
🌐 You can apply CSS styles to the text using the cssOverrides property. This allows you to set properties like text-shadow, text-decoration, and more.
fancy.style.addOverride('text-shadow: 2px 2px 4px rgba(0,0,0,0.5)');
API 参考
🌐 API Reference