動きのあるロゴやアイコンを、Webサイトに入れたい場合は「Lottie(ロッティ)」を使うことで表示できます。
After Effectsで作ったアニメーションを軽量なJSON形式で、Web上に表示してみたいと思ったので実装内容を備忘録として残しておきます。
動くロゴは本サイトの「ホームページ公開までの流れ」で使っています。
今回の構成はこんな感じです。
project-root/
├─ index.html
├─ js/main.js
├─ img/json/icon1.json
Lottieアニメーションを表示するには、アニメーションを読み込む「div」を用意しておきます。
それぞれに id をつけておくことで、JavaScriptから個別に制御できます。
<div id="logo1" style="width:100px;height:100px;"></div>
<div id="logo2" style="width:100px;height:100px;"></div>
<div id="logo3" style="width:100px;height:100px;"></div>HTML<head> または <body> の中で、Lottie用のライブラリを読み込みます。
<script src="https://unpkg.com/lottie-web@latest/build/player/lottie.min.js"></script>
<!-- こちらも忘れずにHTML内に読み込む -->
<script src="js/main.js"></script>HTMLCDNはこちらからhttps://cdnjs.com/libraries/lottie-web
main.jsファイルに以下のコードを書きます。
複数のJSONファイルを読み込むには、配列とforEach()を使うと効率的です。
const animations = [
{ id: 'logo1', path: '../img/json/icon1.json' },
{ id: 'logo2', path: '../img/json/icon2.json' },
{ id: 'logo3', path: '../img/json/icon3.json' }
];
animations.forEach(anim => {
lottie.loadAnimation({
container: document.getElementById(anim.id),
renderer: 'svg',
loop: true,
autoplay: true,
path: anim.path
});
});
//ワードプレスの場合のパスは以下
//{ id: 'logo1', path: '/wp-content/themes/テーマ名/img/json/icon1.json' },
JavaScriptこれだけで本サイトの「ホームページ公開までの流れ」のような動くアイコンを、web上に反映することができます。
animations という配列に、複数のアニメーションの情報(IDとJSONファイルのパス)が入っていて、それを1つずつ読み込んで再生するという処理です。
animations.forEach(anim => {
lottie.loadAnimation({
container: document.getElementById(anim.id),
renderer: 'svg',
loop: true,
autoplay: true,
path: anim.path
});
});JavaScriptanimations.forEach(anim => { … })
つまり、「配列の中身を1つずつ取り出して処理するよー」という意味です。
lottie.loadAnimation({ … })
これは Lottie の公式関数で、JSONファイルを読み込んでアニメーションを表示するための関数です。
container: document.getElementById(anim.id)
renderer: ‘svg’
loop: true
autoplay: true