布局
Fit 模式
Fit 决定了画板内容如何适应可用的画布空间。你可以通过 Layout 对象设置 Fit 和对齐方式。
Alignment(对齐方式)
Alignment 控制画板在其画布内的定位方式。可用的对齐选项包括 TopLeft、TopCenter、TopRight、CenterLeft、Center、CenterRight、BottomLeft、BottomCenter、BottomRight。
Bounds(边界)
你可以选择为布局设置边界,以约束画板的可渲染区域。
应用 Fit 模式
使用 Layout 对象配置 Fit 和 Alignment。所有枚举选项请参见 Fit 和 Alignment。
import Rive, { Layout, Fit, Alignment } from '@rive-app/react-canvas';
export const Simple = () => (
<Rive
src="https://cdn.rive.app/animations/vehicles.riv"
layout={new Layout({ fit: Fit.Contain, alignment: Alignment.TopCenter })}
/>
);
使用 useRive Hook:
import { useRive, Layout, Fit, Alignment } from '@rive-app/react-canvas';
export default function Example() {
const { RiveComponent } = useRive({
src: 'my-file.riv',
artboard: 'my-artboard',
animations: 'my-animation',
layout: new Layout({
fit: Fit.Cover,
alignment: Alignment.TopCenter,
}),
autoplay: true,
});
return <RiveComponent />;
}
响应式布局
步骤
- 在
Layout对象中将fit设置为Fit.Layout— 这将自动缩放和调整画板大小以匹配画布大小。 - 将
Layout对象传入useRive的layout属性。 - (可选)在
Layout对象中设置layoutScaleFactor以手动控制画板的缩放因子。 - React 运行时会自动处理窗口大小调整和设备像素比变化。
import { useRive, Layout, Fit } from "@rive-app/react-canvas";
export const RiveComponent = () => {
const { RiveComponent } = useRive({
src: "your-rive-file.riv",
stateMachines: "State Machine 1",
layout: new Layout({
fit: Fit.Layout,
// layoutScaleFactor: 2, // 可选:布局的 2 倍缩放
}),
autoplay: true,
});
return <RiveComponent />;
};