富文本

阅读时间:2分钟更新于 2025-06-12 17:56

富文本元素支持在 Player 播放的任意时刻完成变化,文本元素在使用上绝大部分都是一样的,只存在个别 API 接口的区别。

插件引入

需要额外接入 插件(请确保插件版本号与 @galcean/effects 版本号一致)。

$ npm i @galacean/effects-plugin-rich-text --save
import { Player } from '@galacean/effects';
// 确保在 @galacean/effects 引入之后再引入插件, 插件版本保持和 @galacean/effects 一致
import '@galacean/effects-plugin-rich-text';

如何动态变化文字

loadScene 之后,就可以对富文本元素进行文字内容的变更,以下图的 richText_2 为例:

  • ⚠️ 强烈建议使用英文作为富文本元素的名称!!

开发获得到富文本元素的名称后就可以进行文本相关的参数设置了,下面以修改文本的文案举例(textName为上图中的'richText_2'):

  • 加载时变更富文本元素文案:
// 与设计同学约定的文本名称为 textName

// 加载动画资源并播放
const composition = await player.loadScene(myAnimation, {
  variables: {
    textName: '<color=#ef951aff>Galacean\nEffects\n\n富文本</color>',
  },
});
  • 播放过程中修改富文本元素文案:
import { TextComponent, spec } from '@galacean/effects';

// 播放期间修改富文本元素文案
// 查找富文本元素组件,请确保 textName 在产物中存在
const text = composition.getItemByName('textName')?.getComponent(TextComponent);

// overflow 默认为 clip,即:当文本内容超出边界框时,多余的会被截断。
// 因此,多行文本中,为避免出现超出边界被截断的情况,可以设置 overflow 为 display,这样会自动调整文本字号以适配完整显示。
text?.setOverflow(spec.TextOverflow.display);
// 变更文案
text?.setText('<color=#ef951aff>Galacean</color> <b>Effects</b>\n<color=#00ff00ff><i>富文本</i></color>');

富文本的代码内容可以在编辑器复制

支持的样式标签

  • <b>粗体</b>
  • <i>斜体</i>
  • <size>字号</size>
  • <color>文字颜色</color>

文本清晰度调整

  • 播放过程中修改文本清晰度:
// 播放期间修改富文本元素文案
// 查找富文本元素组件,请确保 textName 在产物中存在
const text = composition.getItemByName('textName')?.getComponent(TextComponent);

// 变更清晰度
text?.setFontScale(2);

其他用法 API

普通文本

注意: API 接口为非特殊设置文本外的全局设置

Preview