跳到主要内容

布局

Fit 模式

Fit 决定了画板内容如何适应可用的画布空间。你可以通过 Layout 对象设置 Fit 和对齐方式。

Alignment(对齐方式)

Alignment 控制画板在其画布内的定位方式。可用的对齐选项包括 TopLeftTopCenterTopRightCenterLeftCenterCenterRightBottomLeftBottomCenterBottomRight

Bounds(边界)

你可以选择为布局设置边界,以约束画板的可渲染区域。

应用 Fit 模式

使用 Layout 对象配置 FitAlignment。所有枚举选项请参见 FitAlignment

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 />;
}

响应式布局

步骤

  1. Layout 对象中将 fit 设置为 Fit.Layout — 这将自动缩放和调整画板大小以匹配画布大小。
  2. Layout 对象传入 useRivelayout 属性。
  3. (可选)在 Layout 对象中设置 layoutScaleFactor 以手动控制画板的缩放因子。
  4. 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 />;
};