Lottie × React:WebアプリにLottieアニメーションを組み込む完全ガイド

Lottie×ReactでWebアニメーション実装

AfterEffectsで作ったアニメーションをWebで動かす——これがLottieのコアな価値だ。Reactとの組み合わせは特に相性がよく、コンポーネントベースで再利用可能なアニメーションを簡単に実装できる。この記事では実務レベルの実装パターンを解説する。

必要なパッケージ

npm install lottie-react
# または軽量版(コントロール機能なし)
npm install @lottiefiles/react-lottie-player

基本的な使い方

// components/LottieAnimation.tsx
import Lottie from "lottie-react";
import animationData from "../assets/my-animation.json";

export function LottieAnimation() {
  return (
    <Lottie
      animationData={animationData}
      loop={true}
      autoplay={true}
      style={{ width: 300, height: 300 }}
    />
  );
}

再生コントロール:useRefで操作する

import Lottie, { LottieRefCurrentProps } from "lottie-react";
import { useRef } from "react";

export function ControllableAnimation() {
  const lottieRef = useRef<LottieRefCurrentProps>(null);

  return (
    <div>
      <Lottie
        lottieRef={lottieRef}
        animationData={animationData}
        loop={false}
        autoplay={false}
      />
      <button onClick={() => lottieRef.current?.play()}>再生</button>
      <button onClick={() => lottieRef.current?.pause()}>一時停止</button>
      <button onClick={() => lottieRef.current?.stop()}>停止</button>
      <button onClick={() => lottieRef.current?.setSpeed(2)}>2倍速</button>
    </div>
  );
}

スクロール連動アニメーション

スクロール位置に合わせてアニメーションを再生する実装は、LPや紹介ページで効果的だ。

import { useEffect, useRef, useState } from "react";
import Lottie, { LottieRefCurrentProps } from "lottie-react";

export function ScrollLinkedAnimation() {
  const lottieRef = useRef<LottieRefCurrentProps>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleScroll = () => {
      if (!containerRef.current || !lottieRef.current) return;
      const rect = containerRef.current.getBoundingClientRect();
      const windowHeight = window.innerHeight;

      // 要素が画面内にある割合(0〜1)
      const progress = Math.max(0, Math.min(1,
        (windowHeight - rect.top) / (windowHeight + rect.height)
      ));

      // フレーム数を取得して割合を掛ける
      const totalFrames = lottieRef.current.getDuration(true) ?? 0;
      lottieRef.current.goToAndStop(progress * totalFrames, true);
    };

    window.addEventListener("scroll", handleScroll, { passive: true });
    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  return (
    <div ref={containerRef} style={{ height: "200vh" }}>
      <div style={{ position: "sticky", top: "20vh" }}>
        <Lottie
          lottieRef={lottieRef}
          animationData={animationData}
          autoplay={false}
          loop={false}
        />
      </div>
    </div>
  );
}

LottieFilesからアニメーションを動的に読み込む

import { useState, useEffect } from "react";
import Lottie from "lottie-react";

interface Props { animationUrl: string; }

export function DynamicLottie({ animationUrl }: Props) {
  const [animationData, setAnimationData] = useState<object | null>(null);

  useEffect(() => {
    fetch(animationUrl)
      .then(res => res.json())
      .then(setAnimationData);
  }, [animationUrl]);

  if (!animationData) return <div>Loading...</div>;
  return <Lottie animationData={animationData} loop autoplay />;
}

// 使用例
<DynamicLottie animationUrl="https://assets.lottiefiles.com/packages/lf20_xxx.json" />

JSON内のテキスト・カラーを動的に変更する

Lottie JSONの構造を直接操作することで、テキストや色をReactのstateで動的に変更できる。

// Lottie JSONのカラーを動的に変更するユーティリティ
function changeLottieColor(
  animationData: any,
  layerName: string,
  newColor: [number, number, number]  // RGB 0〜1
): any {
  const clone = JSON.parse(JSON.stringify(animationData));
  const layers = clone.layers ?? [];

  layers.forEach((layer: any) => {
    if (layer.nm === layerName) {
      // ソリッドレイヤーの場合
      if (layer.sc) {
        const [r, g, b] = newColor;
        layer.sc = `#${Math.round(r*255).toString(16).padStart(2,"0")}${Math.round(g*255).toString(16).padStart(2,"0")}${Math.round(b*255).toString(16).padStart(2,"0")}`;
      }
    }
  });
  return clone;
}

// 使用例
const brandedAnimation = changeLottieColor(rawAnimationData, "Background", [0.2, 0.6, 1.0]);

パフォーマンス最適化:不要な再レンダリングを防ぐ

// useMemoでanimationDataをメモ化
import { useMemo } from "react";

export function OptimizedLottie() {
  const animationData = useMemo(() => require("../assets/animation.json"), []);

  return <Lottie animationData={animationData} loop autoplay />;
}

AfterEffectsからの書き出し品質を上げるコツ

  • シェイプレイヤー中心で作る:ビットマップ素材はLottieで重くなる
  • エクスプレッションは最小限に:サポートされていないエクスプレッションは無視される
  • Precompを展開して書き出す:Bodymovinプラグインの「Flatten precomps」オプションを使う
  • フレームレートは24fpsで統一:Webでは24fpsが標準的で軽量

まとめ

lottie-reactを使えば、AfterEffectsで作ったアニメーションをReactコンポーネントとして再利用できる。スクロール連動・動的カラー変更・動的テキスト差し込みも実装可能で、Webサービスのブランドアニメーションとして非常に有効だ。まずは基本的な再生コントロールから試してほしい。

あわせて読みたい

ツール導入で終わらない「本当のDX」を、一緒に作りませんか

AE→Lottie→Remotionの動画自動生成から、業務プロセス全体の自動化まで。
自分で作って動かしている仕組みを、あなたのビジネスにも実装します。

プロダクト・サービス一覧開発実績を見る
タイトルとURLをコピーしました