🪕

Lottieで簡単にWebアニメーションを追加する方法

2022/10/09に公開

はじめに

LottieとはAirBnbの開発したライブラリ及びベクターアニメーションのファイル形式のことです。データがJSONで記述されるため、ファイル容量が軽く、プログラムより柔軟にアニメーションを制御することもできます。

ちなみにDuolingoのアニメーションにもLottieが使われていたりします。

公式サイト:https://airbnb.design/lottie/

アニメーションの作成方法

アニメーションの作成にはAfter Effectsを利用します。アニメーションが完成したらBodyMovin というエクステンションを使用して書き出します。
ただし、利用できるAfter Effectsの機能には制限があるため注意です。1フレームずつトレースすることで生成することも可能のようです。利用できる機能の一覧はこちらを確認してください。

...自分にはアニメーションを自分で作るハードルが高すぎる!!という方は https://lottiefiles.com/ を使いましょう。他ユーザーの作ってくれたアニメーションを借りてくるもできます。

利用方法

Webの中にLottieを埋め込むにはlottie-web(リポジトリ:https://github.com/airbnb/lottie-web)というライブラリが使います。

npm install lottie-web

もしくはCDNから読み込む方法もあります。
https://cdnjs.com/libraries/bodymovin

サンプル(ドキュメントからコピペ)

lottie.loadAnimation({
  container: element, // the dom element that will contain the animation
  renderer: 'svg',
  loop: true,
  autoplay: true,
  path: 'data.json' // the path to the animation json
});

loadAnimationからインスタンスが帰ってくるので、それを使ってアニメーションを制御します。

Reactでの利用方法

lottie-reactを利用する

これが最も手っ取り早くて簡単な方法です。
AirBnbの提供するlottie-reactというライブラリを利用します。
https://github.com/LottieFiles/lottie-react

npm install @lottiefiles/react-lottie-player

サンプル(ドキュメントより引用)

import React from 'react';
import { Player } from '@lottiefiles/react-lottie-player';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.player = React.createRef(); // initialize your ref
  }
  render() {
    return (
      <Player
        ref={this.player} // set the ref to your class instance
        autoplay={false}
        loop={true}
        controls={true}
        src="https://assets3.lottiefiles.com/packages/lf20_XZ3pkn.json"
        style={{ height: '300px', width: '300px' }}
      ></Player>
    );
  }
}

export default App;

上のサンプルではsrcにURLを設定していますが、animationDataにJSONそのものを突っ込むこともできるのですが、その際、アニメーションを繰り返し再生するには、データをディープクローンしてから渡す必要があります。

Discussion