Lottieアニメーションの再生、一時停止、停止をJavaScriptで制御するコードを紹介します。
こちらの記事では、
Bodymovin で出力した LottieアニメーションをWebページで再生するHTMLを紹介しました。
紹介した方法ではページを読み込むと自動でアニメーションの再生が始まりますが、
利用用途によっては、アクションが発生したタイミングでアニメーションを再生したい場合があります。
この記事では、LottieアニメーションをJavaScriptで再生、一時停止、停止するコードを紹介します。
Lottieアニメーションを再生する場合は、Animationオブジェクトインスタンスの play()
メソッドを利用します。
書式は次の通りです。
(Animationオブジェクトインスタンス).play();
アニメーションを一時停止する場合は、Animationインスタンスの pause()
メソッドを利用します。
(Animationオブジェクトインスタンス).pause();
アニメーションを停止する場合は、Animationインスタンスの stop()
メソッドを利用します。
(Animationオブジェクトインスタンス).stop();
以下のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.10.2/lottie.min.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = animation_init;
var animation;
function animation_init() {
animation = bodymovin.loadAnimation({
container: document.getElementById('frame'),
renderer: 'svg',
loop: true,
autoplay: false,
path: 'data.json'
});
}
function animation_start() {
animation.play();
}
function animation_pause() {
animation.pause();
}
function animation_stop() {
animation.stop();
}
</script>
<style type="text/css">
#frame {
width: 180px;
}
</style>
</head>
<body>
<h2>Lottie アニメーションの開始と停止</h2>
<button onclick="animation_start();">Play</button>
<button onclick="animation_pause();">Pause</button>
<button onclick="animation_stop();">Stop</button>
<hr />
<div id="frame"></div>
</body>
</html>
以下のコードでAnimationオブジェクトのインスタンスを作成しています。
今回はアクションでアニメーションを再生するため、loop
プロパティをtrueに設定し、autoplay
プロパティをfalseに設定し、
アニメーションが自動で開始しない状態に設定します。
window.onload = animation_init;
var animation;
function animation_init() {
animation = bodymovin.loadAnimation({
container: document.getElementById('frame'),
renderer: 'svg',
loop: true,
autoplay: false,
path: 'data.json'
});
}
以下はアニメーションを制御する関数です。
Animationインスタンスのplay, pause, stopメソッドを呼び出す関数を実装しています。
function animation_start() {
animation.play();
}
function animation_pause() {
animation.pause();
}
function animation_stop() {
animation.stop();
}
HTMLページにはアニメーションを再生する枠(id="frame"のdivタグ)と、アニメーションを制御するボタンを配置しています。
ボタンをクリックすると、アニメーションを制御する関数を呼び出します。
<h2>Lottie アニメーションの開始と停止</h2>
<button onclick="animation_start();">Play</button>
<button onclick="animation_pause();">Pause</button>
<button onclick="animation_stop();">Stop</button>
<hr />
<div id="frame"></div>
上記のHTMLファイルをWebブラウザで表示します。
下図のページが表示されます。アニメーションは再生されず最初のフレームで止まった状態でページが表示されます。
ページ内の[Play]ボタンをクリックするとアニメーションが再生されます。
[Pause]ボタンをクリックするとアニメーションが一時停止します。
再度[Play]ボタンをクリックすると、アニメーションが再開されます。
アニメーションが最後まで再生し終わると、最初のフレームに戻りアニメーションの再生が繰り返されます。
[Stop]ボタンをクリックするとアニメーションの再生が停止になり、最初のフレームの状態に戻ります。
JavaScriptを利用して、Lottieのアニメーションの再生や停止の制御ができました。