动画播放
⚠️ 已弃用:请在运行时使用状态机代替直接动画播放
选择起始动画
要将 Rive 实例默认设置为特定动画,可以在 Rive 参数中传入 animations 选项。
// 播放 idle 动画
export const Simple = () => (
<Rive src="https://cdn.rive.app/animations/vehicles.riv" animations="idle" />
);
// 使用 `useRive` Hook:
export default function Simple() {
const { RiveComponent } = useRive({
src: 'https://cdn.rive.app/animations/vehicles.riv',
animations: ['idle'],
autoplay: true,
});
return <RiveComponent />;
}
控制播放
调用播放控制
与 Web 非常相似,你可以传入 Rive 参数和某些动画事件的回调。有关可设置的回调示例,请参见 Web 标签页。此外,你可以使用 useRive Hook 返回的 rive 对象来调用播放控制。
参见以下示例:https://codesandbox.io/p/sandbox/adoring-sea-n7m59f
import { useState } from "react";
import { useRive, Layout, Fit } from "@rive-app/react-canvas";
export default function App() {
const [truckButtonText, setTruckButtonText] = useState("Start Truck");
const [wiperButtonText, setWiperButtonText] = useState("Start Wipers");
// 动画将显示第一帧但不会开始播放
const { rive, RiveComponent } = useRive({
src: "https://cdn.rive.app/animations/vehicles.riv",
artboard: "Jeep",
layout: new Layout({ fit: Fit.Cover }),
// 监听播放事件以更新按钮文本
onPlay: (event) => {
const names = event.data;
names.forEach((name) => {
if (name === "idle") {
setTruckButtonText("Stop Truck");
} else if (name === "windshield_wipers") {
setWiperButtonText("Stop Wipers");
}
});
},
// 监听暂停事件以更新按钮文本
onPause: (event) => {
const names = event.data;
names.forEach((name) => {
if (name === "idle") {
setTruckButtonText("Start Truck");
} else if (name === "windshield_wipers") {
setWiperButtonText("Start Wipers");
}
});
},
});
function onStartTruckClick() {
if (rive) {
if (rive.playingAnimationNames.includes("idle")) {
rive.pause("idle");
} else {
rive.play("idle");
}
}
}
function onStartWiperClick() {
if (rive) {
if (rive.playingAnimationNames.includes("windshield_wipers")) {
rive.pause("windshield_wipers");
} else {
rive.play("windshield_wipers");
}
}
}
return (
<>
<div>
<RiveComponent style={{ height: "1000px" }} />
</div>
<div>
<button id="idle" onClick={onStartTruckClick}>
{truckButtonText}
</button>
<button id="wipers" onClick={onStartWiperClick}>
{wiperButtonText}
</button>
</div>
</>
);
}