SVGアニメーション – Web Animations API を使う – Element.animate()メソッドの options – duration について
前回の投稿に続き、Element.animate()メソッド の options について試してみます。
options – duration について
options の duration は keyframes の状態の定義(サンプルでは5パターン)を、何秒かけて実行するかを決めます。
単位はミリ秒で、duration: 5000 と指定すれば、5秒間かけて全ての定義の状態に変化します。
以下に、duration の値を動的に指定するサンプルを書いて試してみます。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
.params_box {
font-size : 0.8em;
}
.range {
width: 400px;
}
.code_view {
font-size : 0.8em;
padding: 5px;
background-color: #000000;
color: #ffffff;
}
#code_view1 {
color: #ff0000;
}
</style>
</head>
<body>
<svg xmlns="http://www.w3.org/2000/svg"
width = "500"
height = "100"
viewBox = "0 0 500 100"
>
<rect
id = "recttest"
x = "0"
y = "0"
width = "100"
height = "70"
fill = "#999"
/>
</svg>
<div>
<div class="params_box">
<span>duration : </span><span class="params" id="range1_value"></span>
<div><input type="range" class="range" id="range1" value="0" max="100000"></div>
</div>
</div>
<div class="code_view">
// アニメーション処理を実行(javascriptから抜粋)<br />
const options = {<br />
duration: "<span id="code_view1"></span>"<br />
iterations: Infinity<br />
};<br />
<br />
dom_rect.animate(keyframes, options);<br />
</div>
<script>
// アニメーション対象のDOM要素を取得
let dom_recttest = document.querySelector("#recttest");
let animation;
// スライダの要素を取得し、イベントを付与する
let dom_range1 = document.querySelector('#range1');
// 各スライダーごとのイベントに、共通の関数を割り当てて処理する
dom_range1.addEventListener('input', change_range_slider);
// スライダーを動かした時の処理
function change_range_slider()
{
console.log("dom_range1.value -> " + dom_range1.value);
if (animation) {
animation.pause(); // アニメーションを一時停止
}
// アニメーションのオプションを取得
const currentOptions = {
duration: parseInt(dom_range1.value),
iterations: Infinity
};
// アニメーションを再設定
animation = dom_recttest.animate(keyframes, currentOptions);
// パラメータ値をHTML出力
let range1_value_dom = document.querySelector('#range1_value');
range1_value_dom.innerHTML = (dom_range1.value / 1000) + "秒";
let code_view1_dom = document.querySelector('#code_view1');
code_view1_dom.innerHTML = dom_range1.value;
}
// keyframesの定義
const keyframes = [
{width:'100px', height:'70px', fill:'#999999'}, // グレー
{width:'50px' , height:'5px' , fill:'#3399FF'}, // ブルー
{width:'450px', height:'80px', fill:'#FF9900'}, // オレンジ
{width:'0px' , height:'0px' , fill:'#00CC00'}, // グリーン
{width:'100px', height:'70px', fill:'#FF3300'} // レッド
];
// アニメーション処理を実行
const options = {
duration: 5000,
iterations: Infinity
};
dom_recttest.animate(keyframes, options);
</script>
</body>
</html>
画面にアクセスすると、アニメーションはデフォルト値の5000ミリ秒の再生時間でアニメーションされます。
画面上のスライダーを調整すると、duration の値を「0ミリ秒」から「100000ミリ秒」の範囲で変更することができます。
スライダーを変更すると、アニメーションの再生がリセットされ、総再生時間を動的に変更した場合の変化を確認できます。
0ミリ秒にすると、アニメーションは再生されていますが、変化する時間が極端に短い(0の為)、目視でアニメーションを確認することは困難です。
また、スライダを最大の「100000ミリ秒」(100秒)にすると、5つの状態変化を100秒かけて変化することが確認できます。