Framer Motion 整合
Framer Motion 動畫通常是基於時間的。若要與 Helios(基於幀且可拖曳)同步,必須將 Helios 的幀狀態映射到 MotionValue。
快速開始
1. useVideoFrame Hook
確保你已有 useVideoFrame Hook(請參閱 examples/react/SKILL.md)。
2. 將幀映射到 MotionValue
使用 useTransform 將當前幀(來自 useVideoFrame)映射到動畫值。
import { useMotionValue, useTransform, motion } from 'framer-motion';
import { useVideoFrame } from './hooks/useVideoFrame';
export const MyComponent = ({ helios }) => {
// 1. 取得當前幀
const frame = useVideoFrame(helios);
// 2. 為幀建立一個 MotionValue
const frameMv = useMotionValue(0);
// 當幀改變時同步 MotionValue
useEffect(() => {
frameMv.set(frame);
}, [frame, frameMv]);
// 3. 將幀轉換為動畫值
// 範例:在 60 幀內旋轉 360 度(0 到 60)
const rotate = useTransform(frameMv, [0, 60], [0, 360]);
// 範例:在前 30 幀淡入
const opacity = useTransform(frameMv, [0, 30], [0, 1]);
return (
<motion.div
style={{
width: 100,
height: 100,
background: 'blue',
rotate, // 繫結轉換後的值
opacity
}}
/>
);
};
進階:手動設定 MotionValue
為提升深層元件的效能,請直接在訂閱中更新共用的 MotionValue,繞過 React 狀態。
const frameMv = useMotionValue(0);
useEffect(() => {
const unsubscribe = helios.subscribe((state) => {
// 直接更新 MotionValue - 不觸發 React 重新渲染!
frameMv.set(state.currentFrame);
});
return unsubscribe;
}, [helios, frameMv]);
const x = useTransform(frameMv, [0, 100], [0, 500]);
return <motion.div style={{ x }} />;
原始檔
- 範例:
examples/framer-motion-animation/