SVGアニメーション – Web Animations API を使う – アニメーション実行時のstartTimeプロパティについて
startTimeプロパティはアニメーションする要素の再生開始タイミングを決定します。
また、サンプルでも動作させていますが、startTimeプロパティの値を決定した後、
アニメーションが再生されるまでcurrentTime(現在の再生位置)がマイナスからカウントダウンされるように表示されます。
例えば再生開始(startTime)が5秒後の場合は、現在の再生位置(currentTime)は-5秒から0に減っていきます。
再生開始タイミングがどのように影響するかを確認できる簡単なサンプルを用意しました。
スライダ位置を調整すると自動的にN秒(スライダ値)後にアニメーションが開始されます。
画面内にはN秒後にアニメーション再生される秒数表示と、現在の再生位置(N秒)がわかる秒数表示をしています。
秒数表示は0.01秒ごと画面描画しています。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
#bottom {
margin-bottom : 10px;
}
#test1_dom {
color : #5f5d5d;
background-color : #cccccc;
font-size : 1.1rem;
width : 150px;
}
.range {
width: 100%; /* スライダーの幅を画面最大に */
}
</style>
</head>
<body>
<!-- 開始ボタン -->
<div id="bottom">
<input type="button" id="start_animate" value="アニメーション開始">
<input type="button" id="cancel_animate" value="アニメーション停止">
</div>
<!-- スライダ -->
<div class="params_box">
<span class="param_title">再生開始(startTime)</span>
<div><input type="range" class="range" id="range1" value="0" max="1000"></div>
<span class="params" id="range1_value"></span>
</div>
<!-- アニメーション用DIV -->
<div id="test1_dom">TEST1 (<span id="display"></span>)</div>
<!-- 再生秒数 -->
<div class="params" id="currentTime_value"></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秒で一周
};
animation1 = test1_dom.animate(keyframes1, options1);
animation1.cancel(); // 初期値は停止
// アニメーション開始
start_animate_dom.addEventListener('click', (e) => {
// 開始ボタン押下でスライダ移動した挙動を同じ動きをする
change_range_slider();
}, false);
// アニメーション停止
cancel_animate_dom.addEventListener('click', (e) => {
animation1.cancel();
display_dom.innerHTML = animation1.playState;
}, false);
// スライダ値を取得しイベントを付与する
range1_dom.addEventListener('input', change_range_slider);
function change_range_slider()
{
// 設定値を画面出力
document.getElementById('range1_value').innerHTML = (range1_dom.value / 10) + '秒後に再生する';
// 一旦アニメーションを停止する
animation1.cancel();
// アニメーションの再生位置を変更する
animation1.startTime = animation1.timeline.currentTime + (range1_dom.value * 100);
// divタグの状態を出力する
display_dom.innerHTML = animation1.playState;
}
// 再生秒数を定期的に更新する
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>
画面にアクセスしてスライダを操作すると、N秒後にアニメーションが開始されます。
スライダを変更すると都度、N秒後にアニメーションが開始されることと、現在位置としてcurrentTime秒が変化することがわかります。