动态换图

阅读时间:1分钟更新于 2025-02-26 10:49

Galacean Effects 支持动态换图(数据模板)来实现运行时的动态数据。

使用

通过 variable 参数传入,key 为编辑器中设置的字段名,value 为需要显示的数据(图片地址)。

player.loadScene(myAnimation, {
  variables: {
    // 动态图片,支持传入图片地址或地址数组
    background: 'url', // 如果图片加载失败,将会触发加载失败
    image_avatar: ['url', 'fallback_url'], // 如果第一个加载失败,将尝试使用第二个地址,都失败将会触发加载失败
  },
});

注意:

  • 如果使用 WebP 或 AVIF 等可能存在兼容问题的文件格式,请在 variables 务必传入 fallback_url

设置

动态图片

当需要动态变化的内容是图片时,可以将整张图片作为变量。业务使用时开发需要自行控制传入的图片大小,避免网络加载过久。

在【动态换图】面板中,打开【动态换图】开关,填入字段名和图片的 CDN 链接,即可将图片设置为动态变量。开发拿到该图片的字段,就可以将当前图片替换为其他图片。

注意:

  • 字段名与 CDN 链接必须都完成填写,设置才会生效。如果没有字段名或没有 CDN 链接,设置不生效,会默认使用当前图片。
  • 时间轴上的名字和动态换图中的名字可能并不是同一个,因为一张图片存在多个元素引用的情况,请和设计人员提前约定好。

使用 setTexture 方法

1、通过 image 链接直接替换(推荐使用)

推荐方式,当我们想要替换一个图层的图片时,推荐使用这种方式来进行图片的替换。

import { SpriteComponent } from '@galacean/effects';

const composition = await player.loadScene('x.json');
const item = composition.getItemByName('sprite_name');
const component = item.getComponent(SpriteComponent);

// 推荐方式
await component.setTexture('https://image-url');

2、通过创建一个 texture 替换(特定情况使用)

当需要替换多个图层的图片时,并且替换的时同一个图片,可以使用下面这种方式完成替换

import { SpriteComponent } from '@galacean/effects';

const composition = await player.loadScene('x.json');
const item1 = composition.getItemByName('sprite_name1');
const item2 = composition.getItemByName('sprite_name2');
const component1 = item1.getComponent(SpriteComponent);
const component2 = item1.getComponent(SpriteComponent)
// 通过 image 创建一个 texture
const texture = await Texture.fromImage('https://image-url', player.renderer.engine);
// 设置texture
component1.setTexture(texture);
component2.setTexture(texture);
Preview