mcpField
D
dotlottie-web

dotlottie-web

github.com/lottiefilesデザイン・UI931125 回インストール今日更新
リポジトリ

dotlottie-web について

WebプロジェクトへのdotLottieアニメーション導入に関する実装ガイドです。フレームワーク非依存とReact向けのパッケージ選択に加え、Canvas再生、Worker描画、複数アニメーション、操作パターンを扱います。

主な機能

  1. 01WebおよびReact向けパッケージ選択ガイド
  2. 02Canvasベースのアニメーション再生
  3. 03Web Workerによる描画オプション
  4. 04複数アニメーションの.lottieファイル対応
  5. 05再生と操作のパターン

活用シーン

  1. 01Webインターフェースへのアニメーション追加
  2. 02複雑なアニメーション描画のWorker移行
  3. 03ホバー、クリック、スクロール連動再生の実装

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/lottiefiles/dotlottie-web --skill dotlottie-web

インストール後、Claude Code で/dotlottie-webを入力して読み込まれたか確認します。

詳細

dotLottie 実装ガイドライン

dotLottie ランタイムを使用した Lottie アニメーションの実装に精通しています。Web プロジェクトで dotLottie を使用する際は、以下のガイドラインに従ってください。

パッケージの選択

次の場合は @lottiefiles/dotlottie-web を使用します。
  • キャンバスを直接制御する必要がある場合
  • フレームワークに依存しないコードを構築する場合
  • 最高のパフォーマンスが重要な場合
  • バンドルサイズを最小限にしたい場合
次の場合は @lottiefiles/dotlottie-react を使用します。
  • React アプリケーションを構築する場合
  • 宣言的なコンポーネント API を使いたい場合
  • React のライフサイクルとの統合が必要な場合

インストール

# Web (vanilla JS, Vue, Svelte, etc.)
npm install @lottiefiles/dotlottie-web

# React
npm install @lottiefiles/dotlottie-react

基本的な実装

Vanilla JavaScript
import { DotLottie } from '@lottiefiles/dotlottie-web';

const dotLottie = new DotLottie({
  canvas: document.getElementById('canvas') as HTMLCanvasElement,
  src: 'https://example.com/animation.lottie',
  autoplay: true,
  loop: true,
});
React
import { DotLottieReact } from '@lottiefiles/dotlottie-react';

function Animation() {
  return (
    <DotLottieReact
      src="https://example.com/animation.lottie"
      autoplay
      loop
    />
  );
}
インスタンス制御を使った React
import { useRef } from 'react';
import { DotLottieReact } from '@lottiefiles/dotlottie-react';
import type { DotLottie } from '@lottiefiles/dotlottie-web';

function Animation() {
  const dotLottieRef = useRef<DotLottie | null>(null);

  return (
    <DotLottieReact
      src="https://example.com/animation.lottie"
      dotLottieRefCallback={(dotLottie) => (dotLottieRef.current = dotLottie)}
    />
  );
}

.lottie と .json

.json よりも常に .lottie 形式を優先してください。

  • ファイルサイズが小さい(圧縮済み)
  • 1 つのファイルで複数のアニメーションに対応
  • アセットを埋め込み可能(画像、フォント)
  • インタラクティブなステートマシンに対応
  • スロットによるテーマ設定

Web Worker(パフォーマンス向上に推奨)

DotLottieWorker を使用してアニメーションのレンダリングを Web Worker に委ね、UI 操作のためにメインスレッドを空けておきます。

Worker の基本的な使用方法
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';

const dotLottie = new DotLottieWorker({
  canvas: document.getElementById('canvas') as HTMLCanvasElement,
  src: 'https://example.com/animation.lottie',
  autoplay: true,
  loop: true,
});
Worker のグループ化(複数のアニメーション)

デフォルトでは、すべての DotLottieWorker インスタンスが同じ Worker を共有します。workerId を使用して、アニメーションを別々の Worker にグループ化できます。

// Hero animation in its own worker
const heroAnimation = new DotLottieWorker({
  canvas: heroCanvas,
  src: 'hero.lottie',
  workerId: 'hero-worker',
});

// UI animations share a different worker
const buttonAnimation = new DotLottieWorker({
  canvas: buttonCanvas,
  src: 'button.lottie',
  workerId: 'ui-worker',
});
Worker を使用する場合
  • DotLottieWorker を使用する場合

    • 複数のアニメーションを同時に実行する場合
    • レイヤー数が多い複雑なアニメーションの場合
    • 負荷の高い JS 処理と並行してアニメーションを実行する場合
    • メインスレッドのパフォーマンスが重要なモバイルデバイスの場合
  • 通常の DotLottie を使用する場合

    • シンプルなアニメーションを 1 つだけ実行する場合
    • フレームに同期的にアクセスする必要がある場合
    • SSR 環境(Worker を使用できない)場合
Worker を使った React
import { DotLottieWorkerReact } from '@lottiefiles/dotlottie-react';

function Animation() {
  return (
    <DotLottieWorkerReact
      src="animation.lottie"
      autoplay
      loop
      workerId="my-worker" // Optional: dedicate to specific worker
    />
  );
}

ステートマシン(インタラクティブ機能)

ステートマシンを使用すると、コードを記述せずにインタラクティブなアニメーションを実現できます。詳細については、ステートマシンガイドをご覧ください。

const dotLottie = new DotLottie({
  canvas,
  src: 'interactive.lottie', // Contains state machine
  autoplay: true,
});

// Fire events to trigger state transitions
dotLottie.stateMachineFireEvent('click');
dotLottie.stateMachineFireEvent('hover');
dotLottie.stateMachineFireEvent('custom-event');

// Set numeric/boolean/string inputs for state conditions
// See: https://github.com/LottieFiles/dotlottie-web/wiki/dotLottie-State-Machine-Guide#working-with-inputs
dotLottie.stateMachineSetNumericInput('progress', 0.5);
dotLottie.stateMachineSetBooleanInput('isActive', true);
dotLottie.stateMachineSetStringInput('mode', 'dark');
ステートマシンのイベント
  • click - ユーザーのクリック/タップ
  • hover - マウスが要素に入る
  • unhover - マウスが要素から離れる
  • complete - アニメーションの再生完了
  • ステートマシンで定義されたカスタムイベント

スロットによるテーマ設定

スロットを使用すると、実行時に色や値をカスタマイズできます。テーマはdotLottie 2.0 仕様に準拠しています。

const dotLottie = new DotLottie({
  canvas,
  src: 'themed.lottie',
  themeId: 'dark-mode', // Use embedded theme by ID
});

// Or apply theme data directly (JSON string per dotLottie 2.0 spec)
// See: https://dotlottie.io/spec/2.0/#themes
dotLottie.setThemeData(JSON.stringify({
  rules: [
    { id: 'primary-color', value: [1, 0.34, 0.13] }, // RGB values 0-1
  ]
}));

スロットの動的な上書き

スロットを使用すると、型付き API でアニメーションプロパティを実行時にカスタマイズできます。 利用できるスロットの型:color、scalar、vector、gradient、text、image。

主な API:getSlotIds()、getSlotType()、setColorSlot()、setScalarSlot()、 setVectorSlot()、setGradientSlot()、setTextSlot()、resetSlot()、clearSlots()。

各スロット型のコード例、アニメーションのキーフレーム、リセット、一括更新、一般的なユースケース(ブランディング、ダークモード、進捗インジケーター)、React との統合を含む API リファレンス全体については、動的スロットのリファレンスをご覧ください。

マーカーとセグメント

特定のセグメントを再生する
// Play frames 0-60
dotLottie.setSegment(0, 60);
dotLottie.play();

// Play by marker name (defined in animation)
dotLottie.setMarker('intro');
dotLottie.play();
マーカーを取得する
const markers = dotLottie.markers();
// Returns: [{ name: 'intro', start: 0, end: 60 }, ...]

特定のフレームを画像としてレンダリングする

再生が目的のフレームを過ぎないように autoplay: false を設定し、load の後に setFrame() を呼び出します。setFrame() は同期的にレンダリングするため、呼び出し直後にキャンバスと dotLottie.buffer(RGBA の Uint8Array)にそのフレームが正確に反映されます。

ブラウザー
const dotLottie = new DotLottie({ canvas, src: 'animation.lottie', autoplay: false });

dotLottie.addEventListener('load', () => {
  dotLottie.setFrame(42);                        // render frame 42
  const dataUrl = canvas.toDataURL('image/png'); // or canvas.toBlob(cb, 'image/png')
});
Node.js(@napi-rs/canvas)
import fs from 'node:fs';
import { createCanvas } from '@napi-rs/canvas';

const canvas = createCanvas(200, 200);
const dotLottie = new DotLottie({
  canvas: canvas as unknown as HTMLCanvasElement,
  src: 'animation.lottie',
  autoplay: false,
});

dotLottie.addEventListener('load', async () => {
  dotLottie.setFrame(42);
  fs.writeFileSync('frame-42.png', await canvas.encode('png'));
  dotLottie.destroy();
});

独自のエンコードを行う場合は、dotLottie.buffer から RGBA の生ピクセルデータを直接読み取ります(長さ = width × height × 4)。

イベント処理

dotLottie.addEventListener('load', () => {
  console.log('Animation loaded');
});

dotLottie.addEventListener('play', () => {
  console.log('Playing');
});

dotLottie.addEventListener('complete', () => {
  console.log('Animation completed');
});

dotLottie.addEventListener('frame', ({ currentFrame }) => {
  console.log('Frame:', currentFrame);
});

// Clean up
dotLottie.removeEventListener('load', handler);

パフォーマンスに関するベストプラクティス

1. 複雑なアニメーションには Web Worker を使用する
import { DotLottieWorker } from '@lottiefiles/dotlottie-web';

// Offload rendering to worker thread
const dotLottie = new DotLottieWorker({
  canvas,
  src: 'complex-animation.lottie',
});
2. アニメーションを遅延読み込みする
// Only load when visible
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadAnimation();
      observer.disconnect();
    }
  });
});
observer.observe(container);
3. Auto-Freeze はデフォルトで有効

DotLottie は、アニメーションが表示されていないとき(画面外にあるとき)に自動的に停止します。この動作を無効にするには、次のようにします。

const dotLottie = new DotLottie({
  canvas,
  src: 'animation.lottie',
  renderConfig: {
    freezeOnOffscreen: false, // Disable auto-freeze (not recommended)
  },
});
4. デバイスピクセル比

デフォルトでは、パフォーマンス向上のため、devicePixelRatio は実際の値の 75% に設定されます。より高いパフォーマンスコストを許容して、Retina の完全な画質にするには、次のようにします。

const dotLottie = new DotLottie({
  canvas,
  src: 'animation.lottie',
  renderConfig: {
    devicePixelRatio: window.devicePixelRatio, // Full retina (higher CPU/GPU)
  },
});
5. クリーンアップ(Vanilla JS のみ)
// Always destroy when done (vanilla JS)
dotLottie.destroy();

注: DotLottieReact はアンマウント時に自動でクリーンアップを処理するため、手動でクリーンアップする必要はありません。

6. フレーム補間の制御
const dotLottie = new DotLottie({
  canvas,
  src: 'animation.lottie',
  useFrameInterpolation: true,  // Smooth playback (default)
  // useFrameInterpolation: false, // Match original AE frame rate
});

複数のアニメーションを含むファイル

1 つの .lottie ファイルに複数のアニメーションを含めることができます。

// Load specific animation by ID
dotLottie.loadAnimation('animation-2');

// Get all animation IDs
const animations = dotLottie.manifest?.animations;
// Returns: [{ id: 'animation-1' }, { id: 'animation-2' }]

Canvas のサイズ設定

CSS スタイルで Canvas のサイズを設定します(推奨)。DotLottie が最適な描画領域を自動的に判断します。

<canvas id="canvas" style="width: 400px; height: 400px;"></canvas>
コンテナに合わせた自動リサイズ

コンテナのサイズが変わったときに自動でリサイズするには、autoResize レンダリング設定を使用します。

const dotLottie = new DotLottie({
  canvas,
  src: 'animation.lottie',
  renderConfig: {
    autoResize: true, // Canvas resizes to fit container
  },
});

よく使われるパターン

ホバー時に再生
canvas.addEventListener('mouseenter', () => dotLottie.play());
canvas.addEventListener('mouseleave', () => dotLottie.pause());
クリック時に 1 回再生
canvas.addEventListener('click', () => {
  dotLottie.setFrame(0);
  dotLottie.setLoop(false);
  dotLottie.play();
});
スクロールに合わせて再生位置を調整
window.addEventListener('scroll', () => {
  const progress = window.scrollY / (document.body.scrollHeight - window.innerHeight);
  const frame = progress * dotLottie.totalFrames;
  dotLottie.setFrame(frame);
});
読み込み状態(React)
function Animation() {
  const [isLoaded, setIsLoaded] = useState(false);

  return (
    <>
      {!isLoaded && <Skeleton />}
      <DotLottieReact
        src="animation.lottie"
        style={{ opacity: isLoaded ? 1 : 0 }}
        dotLottieRefCallback={(dotLottie) => {
          dotLottie.addEventListener('load', () => setIsLoaded(true));
        }}
      />
    </>
  );
}
レスポンシブアニメーション
function ResponsiveAnimation() {
  return (
    <DotLottieReact
      src="animation.lottie"
      autoplay
      loop
      style={{ width: '100%', maxWidth: '400px' }}
      renderConfig={{ autoResize: true }}
    />
  );
}

デバッグ

// Check if loaded
console.log('Loaded:', dotLottie.isLoaded);

// Get animation info
console.log('Duration:', dotLottie.duration);
console.log('Total Frames:', dotLottie.totalFrames);
console.log('Current Frame:', dotLottie.currentFrame);
console.log('Is Playing:', dotLottie.isPlaying);
console.log('Loop:', dotLottie.loop);
console.log('Speed:', dotLottie.speed);

// Get manifest (for .lottie files)
console.log('Manifest:', dotLottie.manifest);

エラー処理

dotLottie.addEventListener('loadError', (error) => {
  console.error('Failed to load animation:', error);
  // Show fallback UI
});

SSR / Next.js に関する考慮事項

dotLottie にはブラウザー API が必要です。SSR フレームワークでは、以下のようにします。

import dynamic from 'next/dynamic';

const DotLottieReact = dynamic(
  () => import('@lottiefiles/dotlottie-react').then(mod => mod.DotLottieReact),
  { ssr: false }
);

function Animation() {
  return <DotLottieReact src="animation.lottie" autoplay loop />;
}

リソース

コメント