SVGアニメーション – Web Animations API を使う – アニメーション実行中の再生位置について
前回の投稿(https://propansystem.net/blog/9976)で、再生時のステータス値を確認するサンプルを用意しました。
ここでは、再生時の再生位置(秒)を取得するサンプルを書いて試してみます。
再生位置はcurrentTimeプロパティの値を取得することで得られます。
また、下記サンプルでは0.01秒ごとに取得した値を画面描画しています。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
#bottomStart {
margin-bottom : 10px;
}
#test1_dom {
color : #5f5d5d;
background-color : #cccccc;
font-size : 1.1rem;
width : 150px;
}
.range {
width: 100%; /* スライダーの幅を画面最大に */
}
</style>
</head>
<body>
<!-- 開始ボタン -->
<div id="bottomStart">
<input type="button" id="start_animate" value="アニメーション開始">
<input type="button" id="cancel_animate" value="アニメーション停止">
</div>
<!-- 再生秒数の表示 -->
再生秒数:<span class="params" id="currentTime_value"></span>
<!-- アニメーション用DIV -->
<div id="test1_dom">TEST1 (<span id="display"></span>)</div>
<script>
// DOM要素取得
let start_animate_dom = document.querySelector("#start_animate" );
let cancel_animate_dom = document.querySelector("#cancel_animate");
let display_dom = document.querySelector("#display" );
let test1_dom = document.querySelector("#test1_dom" );
let range1_dom = document.querySelector("#range1" );
// アニメーション用オブジェクト
let animation1;
// keyframes定義
const keyframes1 = [
{transform: 'translateX(0px)' },
{transform: 'translateX(500px)'},
];
// option定義
const options1 = {
duration : 10000, // 100秒で一周
iterations : Infinity
};
animation1 = test1_dom.animate(keyframes1, options1);
animation1.cancel(); // 初期値は停止
// アニメーション開始
start_animate_dom.addEventListener('click', (e) => {
animation1.play();
display_dom.innerHTML = animation1.playState;
}, false);
// アニメーション停止
cancel_animate_dom.addEventListener('click', (e) => {
animation1.cancel();
display_dom.innerHTML = animation1.playState;
}, false);
// 再生秒数を定期的に更新する
setInterval(() => {
// アニメーションが再生中の場合に秒数を更新
if (animation1.playState === 'running') {
// currentTimeはミリ秒で返されるので、秒に変換して表示
let disp_sec = (animation1.currentTime / 1000).toFixed(2) + '秒';
document.getElementById('currentTime_value').innerHTML = disp_sec;
}
}, 10); // 0.01秒ごとにチェック
</script>
</body>
</html>
画面にアクセスして「アニメーション開始」ボタンを押下します。
ボタンのすぐ下に「再生秒数」がリアルタイムに表示され、値が取得できていることが確認できます。