Motion & Framer Motion(モーション&フレーマーモーション) は何をしますか?
概要
Motion(旧称Framer Motion)は、ReactおよびJavaScript向けのプロダクションレディなアニメーションライブラリで、最小限のコードで宣言的かつ高性能なアニメーションを実現します。motionコンポーネントを提供し、HTML要素にアニメーション機能を追加するとともに、ジェスチャー認識(ホバー、タップ、ドラッグ、フォーカス)、レイアウトアニメーション、終了アニメーション、スプリング物理などの高度な機能をサポートします。
このスキルを使用するタイミング:
- インタラクティブなUIコンポーネント(ボタン、カード、メニュー)の構築
- マイクロインタラクションやホバーエフェクトの作成
- ページトランジションやルートアニメーションの実装
- スクロールベースのアニメーションやパララックス効果の追加
- レイアウト変更(リサイズ、並べ替え、共有要素トランジション)のアニメーション
- ドラッグ&ドロップインターフェース
- 複雑なアニメーションシーケンスや状態ベースのアニメーション
- CSSトランジションをより強力で制御しやすいアニメーションに置き換える場合
テクノロジー:
- Motion (v11以上) - Framer Motionの開発元によるモダンで小型のライブラリ
- Framer Motion - フル機能の先代ライブラリ(現在も広く使用されています)
- React 18以上互換、Vueもサポート
- TypeScript対応
- Next.js、Vite、Remix、およびすべてのモダンなReactフレームワークで動作
コアコンセプト
1. モーションコンポーネント
任意のHTML/SVG要素をアニメーション可能なコンポーネントに変換するには、先頭にmotion.を付けます:
import { motion } from "framer-motion"
// 通常のHTMLがモーションコンポーネントに
<motion.div />
<motion.button />
<motion.svg />
<motion.path />
すべてのモーションコンポーネントは、animate、initial、transitionなどのアニメーションプロップや、whileHover、whileTapなどのジェスチャープロップを受け入れます。
2. Animateプロップ
animateプロップはターゲットのアニメーション状態を定義します。値が変更されると、Motionは自動的にその値に向けてアニメーションします:
// シンプルなアニメーション - x位置が変更
<motion.div animate={{ x: 100 }} />
// 複数のプロパティ
<motion.div animate={{ x: 100, opacity: 1, scale: 1.2 }} />
// 状態変更時にアニメーション
const [isOpen, setIsOpen] = useState(false)
<motion.div animate={{ width: isOpen ? 300 : 100 }} />
3. 初期状態
initialプロップを使って、アニメーション前の初期状態を設定します:
<motion.div
initial={{ opacity: 0, y: 50 }}
animate={{ opacity: 1, y: 0 }}
/>
initial={false}と設定すると、マウント時の初期アニメーションを無効にできます。
4. トランジション
transitionプロップを使って、アニメーションが状態間でどのように動くかを制御します:
// 時間ベース
<motion.div
animate={{ x: 100 }}
transition={{ duration: 0.5, ease: "easeInOut" }}
/>
// スプリング物理
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring", stiffness: 300, damping: 20 }}
/>
// プロパティごとに異なるトランジション
<motion.div
animate={{ x: 100, opacity: 1 }}
transition={{
x: { type: "spring", stiffness: 300 },
opacity: { duration: 0.2 }
}}
/>
トランジションのタイプ:
"tween"(デフォルト) - イージングを使用した時間ベース"spring"- 物理ベースのスプリングアニメーション"inertia"- 減速アニメーション(ドラッグ時に使用)
5. バリアント
名前付きのアニメーション状態をバリアントとして整理し、コードをよりクリーンにし、子コンポーネントへの伝播を可能にします:
const variants = {
hidden: { opacity: 0, y: 20 },
visible: { opacity: 1, y: 0 },
exit: { opacity: 0, scale: 0.9 }
}
<motion.div
variants={variants}
initial="hidden"
animate="visible"
exit="exit"
/>
バリアントの伝播 - 子コンポーネントは自動的に親のバリアント状態を継承します:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
staggerChildren: 0.1 // 子アニメーションをずらす
}
}
}
const itemVariants = {
hidden: { x: -20, opacity: 0 },
visible: { x: 0, opacity: 1 }
}
<motion.ul variants={containerVariants} initial="hidden" animate="visible">
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
一般的なパターン
1. ホバーアニメーション
whileHoverプロップを使ってホバー時にアニメーションします:
// シンプルなホバーエフェクト
<motion.button
whileHover={{ scale: 1.1 }}
transition={{ duration: 0.2 }}
>
ホバーしてね
</motion.button>
// 複数のプロパティ
<motion.div
whileHover={{
scale: 1.05,
backgroundColor: "#f0f0f0",
boxShadow: "0px 10px 30px rgba(0, 0, 0, 0.2)"
}}
>
ホバーカード
</motion.div>
// カスタムトランジション付き
<motion.button
whileHover={{
scale: 1.2,
transition: { duration: 0.1 } // ジェスチャー開始時のトランジション
}}
transition={{ duration: 0.5 }} // ジェスチャー終了時のトランジション
>
ボタン
</motion.button>
入れ子要素でのホバー:
<motion.div whileHover="hover" variants={cardVariants}>
<motion.h3 variants={titleVariants}>タイトル</motion.h3>
<motion.img variants={imageVariants} />
</motion.div>
2. タップ/プレスアニメーション
whileTapプロップを使ってタップ/プレス時にアニメーションします:
// タップで縮小
<motion.button
whileTap={{ scale: 0.9 }}
>
クリックしてね
</motion.button>
// ホバー+タップの組み合わせ
<motion.button
whileHover={{ scale: 1.1 }}
whileTap={{ scale: 0.95, rotate: 3 }}
>
インタラクティブボタン
</motion.button>
// バリアントを使用
const buttonVariants = {
rest: { scale: 1 },
hover: { scale: 1.1 },
pressed: { scale: 0.95 }
}
<motion.button
variants={buttonVariants}
initial="rest"
whileHover="hover"
whileTap="pressed"
>
ボタン
</motion.button>
3. ドラッグインタラクション
dragプロップを使って要素をドラッグ可能にします:
// 基本的なドラッグ(両軸)
<motion.div drag />
// 軸を制限
<motion.div drag="x" /> // 水平のみ
<motion.div drag="y" /> // 垂直のみ
// ドラッグ制約
<motion.div
drag
dragConstraints={{ left: -100, right: 100, top: -100, bottom: 100 }}
/>
// 親要素で制約
<motion.div ref={constraintsRef}>
<motion.div drag dragConstraints={constraintsRef} />
</motion.div>
// ドラッグ中の視覚的フィードバック
<motion.div
drag
whileDrag={{
scale: 1.1,
boxShadow: "0px 10px 20px rgba(0,0,0,0.2)",
cursor: "grabbing"
}}
dragElastic={0.1} // 制約外ドラッグ時の弾性
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }}
/>
ドラッグイベント:
<motion.div
drag
onDragStart={(event, info) => console.log(info.point)}
onDrag={(event, info) => console.log(info.offset)}
onDragEnd={(event, info) => console.log(info.velocity)}
/>
4. 終了アニメーション(AnimatePresence)
AnimatePresenceを使って、要素がDOMから削除されるときのアニメーションを行います:
import { AnimatePresence } from "framer-motion"
// 基本的な終了アニメーション
<AnimatePresence>
{isVisible && (
<motion.div
key="modal"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
/>
)}
</AnimatePresence>
重要な要件:
- コンポーネントは
<AnimatePresence>の直接の子である必要があります - 一意の
keyプロップが必要です exitプロップを使って終了アニメーションを定義します
終了アニメーション付きリストアイテム:
<AnimatePresence>
{items.map(item => (
<motion.li
key={item.id}
initial={{ opacity: 0, x: -50 }}
animate={{ opacity: 1, x: 0 }}
exit={{ opacity: 0, x: 50 }}
layout // スムーズなレイアウトシフト
>
{item.name}
</motion.li>
))}
</AnimatePresence>
ずらし終了アニメーション:
const containerVariants = {
hidden: { opacity: 0 },
visible: {
opacity: 1,
transition: {
when: "beforeChildren",
staggerChildren: 0.1
}
},
exit: {
opacity: 0,
transition: {
when: "afterChildren",
staggerChildren: 0.05,
staggerDirection: -1 // 逆順
}
}
}
<AnimatePresence>
{show && (
<motion.div variants={containerVariants} initial="hidden" animate="visible" exit="exit">
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
<motion.div variants={itemVariants} />
</motion.div>
)}
</AnimatePresence>
5. レイアウトアニメーション
layoutプロップを使って、位置やサイズの変更を自動的にアニメーションします:
// すべてのレイアウト変更をアニメーション
<motion.div layout />
// 位置変更のみアニメーション
<motion.div layout="position" />
// サイズ変更のみアニメーション
<motion.div layout="size" />
グリッドレイアウトアニメーション:
const [columns, setColumns] = useState(3)
<motion.div className="grid">
{items.map(item => (
<motion.div
key={item.id}
layout
transition={{ layout: { duration: 0.3, ease: "easeInOut" } }}
/>
))}
</motion.div>
共有レイアウトアニメーション (layoutId):
layoutIdを使って、2つの異なる要素を接続し、スムーズなトランジションを実現します:
// タブインジケーターの例
<nav>
{tabs.map(tab => (
<button key={tab.id} onClick={() => setActive(tab.id)}>
{tab.label}
{activeTab === tab.id && (
<motion.div
layoutId="underline"
style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: 2 }}
/>
)}
</button>
))}
</nav>
// サムネイルからモーダルを開く
<motion.img
src={thumbnail}
layoutId="product-image"
onClick={() => setExpanded(true)}
/>
<AnimatePresence>
{expanded && (
<motion.div layoutId="product-image">
<img src={fullsize} />
</motion.div>
)}
</AnimatePresence>
6. スクロールベースのアニメーション
whileInViewを使って、要素がビューポートに入ったときにアニメーションします:
<motion.div
initial={{ opacity: 0, y: 50 }}
whileInView={{ opacity: 1, y: 0 }}
viewport={{ once: true, amount: 0.8 }} // once: 一度だけトリガー, amount: 80%表示
transition={{ duration: 0.5 }}
>
スクロールで表示されたらアニメーション
</motion.div>
ビューポートオプション:
once: true- アニメーションは一度だけトリガーamount: 0.5- 要素が表示される割合(0-1)または"some" | "all"margin: "-100px"- ビューポート境界のオフセット
ずらしスクロールアニメーション:
<motion.ul
initial="hidden"
whileInView="visible"
viewport={{ once: true, amount: 0.3 }}
variants={{
visible: {
opacity: 1,
transition: { staggerChildren: 0.1 }
},
hidden: { opacity: 0 }
}}
>
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
<motion.li variants={itemVariants} />
</motion.ul>
7. スプリングアニメーション
スプリング物理を使って、自然でバウンスのあるアニメーションを実現します:
// 基本的なスプリング
<motion.div
animate={{ scale: 1.2 }}
transition={{ type: "spring" }}
/>
// スプリング物理のカスタマイズ
<motion.div
animate={{ x: 100 }}
transition={{
type: "spring",
stiffness: 300, // 高いほど高速でシャープ(デフォルト: 100)
damping: 20, // 高いほどバウンスが少ない(デフォルト: 10)
mass: 1, // 高いほど慣性が大きい(デフォルト: 1)
}}
/>
// 視覚的持続時間(簡単なスプリング制御)
<motion.div
animate={{ rotate: 90 }}
transition={{
type: "spring",
visualDuration: 0.5, // 知覚される持続時間
bounce: 0.25 // バウンス量(0-1, デフォルト: 0.25)
}}
/>
スプリングプリセット:
- Gentle(優しい):
stiffness: 100, damping: 20 - Wobbly(ふらふら):
stiffness: 200, damping: 10 - Stiff(硬い):
stiffness: 400, damping: 30 - Slow(遅い):
stiffness: 50, damping: 20
ジェスチャー認識
Motionは宣言的なジェスチャーハンドラーを提供します:
ジェスチャープロップ
<motion.div
whileHover={{ scale: 1.1 }} // ポインターが要素にホバー
whileTap={{ scale: 0.9 }} // プライマリポインターが要素をプレス
whileFocus={{ outline: "2px" }} // 要素がフォーカスを取得
whileDrag={{ scale: 1.1 }} // 要素がドラッグ中
whileInView={{ opacity: 1 }} // 要素がビューポート内
/>
ジェスチャーイベント
<motion.div
onHoverStart={(event, info) => {}}
onHoverEnd={(event, info) => {}}
onTap={(event, info) => {}}
onTapStart={(event, info) => {}}
onTapCancel={(event, info) => {}}
onDragStart={(event, info) => {}}
onDrag={(event, info) => {}}
onDragEnd={(event, info) => {}}
onViewportEnter={(entry) => {}}
onViewportLeave={(entry) => {}}
/>
イベント情報オブジェクトには以下が含まれます:
point: { x, y }- ページ座標offset: { x, y }- ドラッグ開始からのオフセットvelocity: { x, y }- ドラッグ速度
フック
useAnimate
useAnimateフックを使ってアニメーションを手動で制御します:
import { useAnimate } from "framer-motion"
function Component() {
const [scope, animate] = useAnimate()
useEffect(() => {
// 複数の要素をアニメーション
animate([
[scope.current, { opacity: 1 }],
["li", { x: 0, opacity: 1 }, { delay: stagger(0.1) }],
[".button", { scale: 1.2 }]
])
}, [])
return (
<div ref={scope}>
<ul>
<li>アイテム 1</li>
<li>アイテム 2</li>
</ul>
<button className="button">クリック</button>
</div>
)
}
アニメーション制御:
const controls = animate(element, { x: 100 })
controls.play()
controls.pause()
controls.stop()
controls.speed = 0.5
controls.time = 0 // 最初にシーク
useSpring
スプリングアニメーションされたモーション値を作成します:
import { useSpring } from "framer-motion"
function Component() {
const x = useSpring(0, { stiffness: 300, damping: 20 })
return (
<motion.div style={{ x }}>
<button onClick={() => x.set(100)}>移動</button>
</motion.div>
)
}
useInView
要素がビューポート内にあるかを検出します:
import { useInView } from "framer-motion"
function Component() {
const ref = useRef(null)
const isInView = useInView(ref, { once: true, amount: 0.5 })
return (
<div ref={ref}>
{isInView ? "ビューポート内!" : "ビューポート外"}
</div>
)
}
統合パターン
GSAPとの連携
Reactの状態ベースアニメーションにはMotionを、複雑なタイムラインにはGSAPを組み合わせます:
import { motion } from "framer-motion"
import gsap from "gsap"
function Component() {
const boxRef = useRef()
const handleClick = () => {
// 複雑なタイムラインにはGSAPを使用
const tl = gsap.timeline()
tl.to(boxRef.current, { rotation: 360, duration: 1 })
.to(boxRef.current, { x: 100, duration: 0.5 })
}
return (
<motion.div
whileHover={{ scale: 1.05 }}
ref={boxRef}
onClick={handleClick}
>
クリックしてGSAPアニメーション
</motion.div>
)
}
パフォーマンスのヒント
変換プロパティを優先
x、y、scale、rotateなどは合成のみをトリガーし、レイアウトやペイントはトリガーしないため、widthやheightよりも優先してください:
// ❌ 非効率 - レイアウトをトリガー
<motion.div animate={{ width: 200, height: 200 }} />
// ✅ 効率的 - 合成のみをトリガー
<motion.div animate={{ scale: 2 }} />
// ✅ より良い - transformの使用
<motion.div
animate={{ x: 100, y: 50, scale: 1.2 }}
/>
不透明度のアニメーション
opacityは合成のみをトリガーするため、高性能です:
<motion.div
animate={{ opacity: 0 }}
transition={{ duration: 0.3 }}
/>
will-changeの使用
styleプロップにwillChangeを追加して、ブラウザに変更を事前に知らせることができます:
<motion.div
animate={{ x: 100 }}
style={{ willChange: "transform" }}
/>
layoutを控えめに
layoutプロップはコストがかかる可能性があるため、必要な場合のみ使用してください:
// 可能な場合はlayoutIdを使用
<motion.div layoutId="shared-element" />
// 小さな変更に制限
<motion.div layout transition={{ duration: 0.2 }} />
トラブルシューティング
アニメーションが動作しない
- コンポーネントに
animateプロップがあることを確認 keyプロップが一意であることを確認(Exitアニメーションの場合)AnimatePresenceが適切にラップしていることを確認
パフォーマンスの問題
- レイアウトプロパティ(
width、height)ではなく、変換プロパティ(transform、opacity)を使用 willChangeでブラウザに最適化を指示- 複雑なアニメーションではバリアントを使用して整理
MotionとFramer Motionの選択
- Motion: 新規プロジェクト用、より小型で高速
- Framer Motion: 既存のコードベースとの互換性が必要な場合
- 移行: インポートパスを
framer-motionからmotionに変更