SVGアニメーション – Web Animations API を使う – Element.animate()メソッドの options – 同一DOM要素に多重にanimate()を適用した場合
同一DOM要素に多重にanimate()を適用した場合、原則「後着優先」で処理されます。
例えば、アニメーション要素が2つあり、
①アニメーション1が10秒かけて色変化する
②アニメーション2が2秒後から5秒かけて色変化する
という場合、
アニメーション開始と同時に①のアニメーションが開始→終了されます。
ただ、この①の処理中に②が同一DOM要素に対してアニメーションされた場合、①のアニメーション要素は打ち消され、②のアニメーションが優先されます。
また、②のアニメーションが短時間で終わる場合は、②のアニメーション終了後に①のアニメーションが引続き継続されます。
以下、簡単なサンプルを用意しました。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
.pseudoElementTest {
color: #000000;
font-size: 1.2rem;
}
</style>
</head>
<body>
<div class="pseudoElementTest">test</div>
<input type="button" id="button_test1" value="pseudoElementTest1">
<script>
// DOM要素を取得
let pseudoElementTest = document.querySelector(".pseudoElementTest");
// アニメーション用
let animation1;
// アニメーション1 keyframesの定義
const keyframes1 = [
{width:'100px', height:'50px', backgroundColor:'#FF6600'}, // オレンジ
{width:'50px' , height:'50px', backgroundColor:'#FFFF00'}, // イエロー
];
// アニメーション2 keyframesの定義
const keyframes2 = [
{width:'100px', height:'50px', backgroundColor:'#0033FF'}, // ブルー
{width:'550px', height:'50px', backgroundColor:'#CC33FF'}, // パープル
];
// botton1
let dom_test1 = document.getElementById('button_test1');
// botton1押下
dom_test1.addEventListener('click', () => {
if (animation1) {
animation1.pause(); // アニメーション1を一時停止
}
const currentOptions1 = {
duration : 10000
};
const currentOptions2 = {
duration : 5000,
delay : 2000,
};
// オプションを再設定する
animation1 = pseudoElementTest.animate(keyframes1, currentOptions1);
// オプションを再設定する
animation1 = pseudoElementTest.animate(keyframes2, currentOptions2);
// アニメーション1の再生と停止
animation1.play();
}, false);
</script>
</body>
</html>
画面アクセスしてボタンを押下すると、アニメーション①が開始されます。
このとき、
「オレンジ → イエロー」の背景色が10秒かけて変化しますが、
2秒後にアニメーション②が開始された際、
「ブルー → パープル」のアニメーション②が優先されて開始することがわかります。
このように options が無指定でデフォルト設定の場合「後着優先」の処理がされることがわかります。
この動きを時系列の表にすると、次のアニメーションと時間の流れになります。
