SVGアニメーション – Web Animations API を使う – timelineについて

javascript

SVGアニメーション – Web Animations API を使う – timelineについて

前回、animationの再生は、以下のように書きました。

var animation = new Animation([effect][, timeline]);

引数のtimelineについて試してみます。
前回のサンプルにtimelineの値を出力してみます。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>

<style>
.animate_timeline_dom {
    background-color: #ebebeb;
}
</style>

</head>
<body>

<input type="button" id="button_1" value="animate timline test">
<div class="animate_timeline_dom">test</div>
<div id="log_disp"></div>

<script>
 
// animate timline testボタンの押下
let dom_button_1 = document.getElementById('button_1');

button_1.addEventListener('click', () => {

	// DOM要素を取得
	let animate_timeline_dom = document.querySelector(".animate_timeline_dom");

	// アニメーションのeffectとtimelineを定義
	animation = animate_timeline_dom.animate(
		[
			{ backgroundColor: '#fff', width:'100px'},
			{ backgroundColor: '#999', width:'50px' },
		],
		{
	    	duration: 8000
	    }
	);

	// timelineの値を出力して確認
	let log_disp_dom = document.getElementById('log_disp');

	const log_output = () => {
		let log_str = "";
		log_str += "animation.timeline.currentTime -> " + animation.timeline.currentTime.toFixed(2) + "<br />";
		log_str += "animation.startTime            -> " + animation.startTime.toFixed(2)            + "<br />";
		log_str += "animation.currentTime          -> " + animation.currentTime.toFixed(2)          + "<br />";
		log_disp_dom.innerHTML = log_str;
	}

	setInterval(log_output, 10);

    // アニメーションの再生
    animation.play();

}, false);
</script>
 
</body>
</html>

サーバ上のHTMLはこちら(test1.html)

画面にアクセスしてanimate timeline test ボタンを押下すると
8秒かけて、domの長さと色が変化するアニメーションが始まります。

ここで注意したい点は

animation.timeline.currentTime
animation.startTime
animation.currentTime

で、それぞれどんな値(秒数)が取得できているかという点です。

currentTimeは画面が表示されてからの秒数がカウントされています。
animation.startTimeは、ボタンを押下してアニメーションが開始された秒数です。
animation.currentTimeは、アニメーションが再生されている秒数で、アニメーションが終了するとリセットされます。

試しに8秒以上経過した後に、もう一度、animate timeline test ボタンを押下する(例では2回押下)とどうなるか、試してみます。

動きを見ると、animation.timeline.currentTime は画面が表示されてからリセットされずに秒数カウントがされてます。
animation.startTime はボタンを押したタイミングでのanimation.timeline.currentTimeの値を取得しています。
animation.currentTimeは上記の例と同様、アニメーションの再生中の秒数をカウントしており、再生が終わるとリセットされていることがわかります。