Skip to main content

HTML 文本

¥HTML Text

HTMLText 允许将样式化、格式化的 HTML 字符串作为 PixiJS 场景图的一部分进行渲染。它使用 SVG <foreignObject> 将浏览器原生 HTML 嵌入到你的 WebGL 画布中。

¥HTMLText enables styled, formatted HTML strings to be rendered as part of the PixiJS scene graph. It uses an SVG <foreignObject> to embed browser-native HTML inside your WebGL canvas.

这使得它非常适合渲染复杂的字体、内联格式、表情符号和布局效果,而这些效果是传统画布渲染文本难以复制的。

¥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> 等。

    ¥✅ Supports inline tags like <b>, <i>, <span>, etc.

  • ✅ 兼容表情符号、Unicode 和 RTL 文本

    ¥✅ Compatible with emojis, Unicode, and RTL text

  • ✅ 通过 CSS 进行细粒度布局控制

    ¥✅ Fine-grained layout control via CSS

  • ✅ 基于标签的样式覆盖(<warning><link> 等)

    ¥✅ Tag-based style overrides (<warning>, <link>, etc.)

异步渲染行为

¥Async Rendering Behavior

HTML 文本使用 SVG <foreignObject> 在画布内绘制 HTML。结果:

¥HTML text uses SVG <foreignObject> to draw HTML inside the canvas. As a result:

  • 渲染异步进行。通常在下一帧之后。

    ¥Rendering occurs asynchronously. Typically after the next frame.

  • 文本内容在实例化后不会立即显示。

    ¥Text content is not immediately visible after instantiation.

HTML 文本样式

¥Styling HTMLText

HTMLTextStyle 扩展了 TextStyle,并添加了以下内容:

¥HTMLTextStyle extends TextStyle and adds:

  • 通过 tagStyles 实现基于 HTML 的标签样式

    ¥HTML-aware tag-based styles via tagStyles

  • 通过 cssOverrides 支持 CSS 覆盖

    ¥CSS override support via cssOverrides

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-shadowtext-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