跳转到内容

动图

相关参考:Scene API / 动图

当前 Web 高级 API 提供了对 GIF 动图对象的创建与播放控制能力。

创建动图

js
const gif = await api.createAnimatedImage('https://your.domain.com/fireworks.gif');
await api.add(gif);

也支持 ArrayBuffer 输入。

播放控制

读取暂停状态

js
const paused = await api.getAnimatedImagePaused(gif);

播放

js
await api.playAnimatedImage(gif, 0);

playAnimatedImage() 还支持第二个参数 loopCount,适合你只希望播放指定次数的场景。

0表示无限循环,不传时则会使用gif文件内置的值

暂停

js
await api.pauseAnimatedImage(gif);

停止

js
await api.stopAnimatedImage(gif);

停止后通常会回到初始状态。

对象事件

  • play - 动图播放时触发
js
function onPlay(event) {
  const { type, target } = event;
}

await api.on('play', onPlay, gif);
  • pause - 动图暂停时触发
js
function onPause(event) {
  const { type, target } = event;
}

await api.on('pause', onPause, gif);
  • ended - 动图自然播放完毕时触发
js
function onEnded(event) {
  const { type, target } = event;
}

await api.on('ended', onEnded, gif);
  • loop - 动图循环播放时,完成某次循环时触发
js
function onEnded(event) {
  // loopedTimes - 已循环的次数
  const { type, target, loopedTimes } = event;
}

await api.on('ended', onEnded, gif);

对象能力与普通图片基本一致

动图对象本质上仍然可以继续使用通用对象 API:

js
await api.setPosition(gif, 0, 1, 0);
await api.setScale(gif, 1.5, 1.5, 1.5);
await api.setObjectVisible(gif, true);

适合什么场景

  • 替代简单粒子特效
  • 做 2D 装饰层
  • 做“点击后短时播放一次”的反馈动画

注意

如果你需要更强的控制粒度,比如逐帧控制、透明通道,通常应优先考虑视频或 glTF 动画,而不是 GIF。