跳到主要内容

动画播放

⚠️ 弃用通知: 本页文档记录了旧的动画播放系统。**对于新项目:**请改用状态机。**对于现有项目:**计划尽快从直接动画控制迁移到状态机。此内容仅供旧版支持参考。

Rive 允许你指定要混合和播放的动画和状态机,并控制每个动画的播放/暂停状态。

术语「动画」可能统指动画和状态机。在本节中,我们探讨如何处理特定动画的播放,而非状态机。

如果你尝试在运行时协调多个动画的播放,请考虑改用状态机来为你完成!

选择起始动画

也可以在实例化 Rive 时选择起始动画。如果未提供,可能会播放画板上的第一个动画,或者未设置状态机。

// 播放 idle 动画
new rive.Rive({
src: 'https://cdn.rive.app/animations/vehicles.riv',
canvas: document.getElementById('canvas'),
animations: 'idle',
autoplay: true
});

控制播放

每个动画和状态机的播放可以分别控制。你可以使用 playpausestop 方法控制播放,可以传入要影响的动画名称,也可以不传参数来影响所有实例化的动画。

调用播放控制

使用 Web 运行时,你可以提供回调函数来接收某些动画事件的通知:

  • onLoad:当 rive 文件加载并初始化完成时触发;此时可以开始播放
  • onPlay:当一个或多个动画播放时触发;提供动画列表
  • onPause:当一个或多个动画暂停时触发;提供动画列表
  • onStop:当一个或多个动画停止时触发;提供动画列表
  • onLoop:当动画循环时触发;提供动画名称

参见以下 Codesandbox 链接来试用下面的代码:https://codesandbox.io/p/sandbox/adoring-sea-n7m59f

const idleButton = document.getElementById("idle");
const wipersButton = document.getElementById("wipers");
const loopDiv = document.getElementById("loop");

const truck = new rive.Rive({
src: "https://cdn.rive.app/animations/vehicles.riv",
artboard: "Jeep",
canvas: document.getElementById("canvas"),
layout: new rive.Layout({ fit: "fill" }),
// 监听播放事件以更新按钮文本
onPlay: (event) => {
const names = event.data;
names.forEach((name) => {
if (name === "idle") {
idleButton.innerHTML = "Stop Truck";
} else if (name === "windshield_wipers") {
wipersButton.innerHTML = "Stop Wipers";
}
});
},
// 监听暂停事件以更新按钮文本
onPause: (event) => {
const names = event.data;
names.forEach((name) => {
if (name === "idle") {
idleButton.innerHTML = "Start Truck";
} else if (name === "windshield_wipers") {
wipersButton.innerHTML = "Start Wipers";
}
});
},
onLoop: (event) => {
loopDiv.innerHTML = `Looped Animation: ${event.data.animation}`;
}
});

idleButton.onclick = (_) =>
truck.playingAnimationNames.includes("idle")
? truck.pause("idle")
: truck.play("idle");

wipersButton.onclick = (_) =>
truck.playingAnimationNames.includes("windshield_wipers")
? truck.pause("windshield_wipers")
: truck.play("windshield_wipers");