Skip to content

Instantly share code, notes, and snippets.

@kobitoDevelopment
Last active April 17, 2023 02:58
Show Gist options
  • Select an option

  • Save kobitoDevelopment/e42312aa4afbcbe843a2b9139c947312 to your computer and use it in GitHub Desktop.

Select an option

Save kobitoDevelopment/e42312aa4afbcbe843a2b9139c947312 to your computer and use it in GitHub Desktop.
<p class="hoge">WebAnimationsAPI</p>
<p>
<span class="start">スタート</span>
<span class="pause">一時停止</span>
<span class="cancel">キャンセル</span>
<span class="reverse">逆再生</span>
<span class="skip">スキップ</span>
</p>
<p class="finish">終了検知</p>
const hoge = document.querySelector(".hoge");
const start = document.querySelector(".start");
const pause = document.querySelector(".pause");
const cancel = document.querySelector(".cancel");
const reverse = document.querySelector(".reverse");
const skip = document.querySelector(".skip");
const end = document.querySelector(".end");
const finish = document.querySelector(".finish");
/* アニメーションを設定 開始*/
// タイムラインを作成
const keyframes = [
{ backgroundColor: "red", transform: "scale(1)", offset: 0.2 /* 0.2 = 20% */ },
{ backgroundColor: "blue", transform: "scale(1)", offset: 0.4 /* 0.4 = 40% */ },
{ backgroundColor: "green", transform: "scale(2)", offset: 1 /* 1 = 100% */ },
];
// configを設定
const config = {
duration: 2000, //アニメーションスピード
easing: "cubic-bezier(1, 0.02, 0, 1.02)", //イージングを設定(ベジェ曲線)
easing: "ease-in-out", //イージングを設定(デフォルトで用意されている種類から利用)
fill: "forwards", //アニメーション終了状態を維持(何も書かなければアニメーション開始前の状態に戻る)
iterations: 1, // 繰り返しの回数を指定。数値で回数、Infinityで無限
};
const animation = hoge.animate(keyframes, config);
// 定義した瞬間にスタートするので停止
animation.pause();
/* アニメーションを設定 終了*/
// スタート
start.addEventListener("click", function () {
animation.playbackRate = 1; //再生の速度比率を設定 1で等速、2で2倍速、-で逆再生
animation.play();
});
// 一時停止
pause.addEventListener("click", function () {
animation.pause();
});
// キャンセル(アニメーション開始前に戻る)
cancel.addEventListener("click", function () {
animation.cancel();
});
// 逆再生(アニメーション開始前に戻る)
reverse.addEventListener("click", function () {
animation.playbackRate = 1; //逆再生の速度比率を設定 1で等速、2で2倍速、-で逆再生
animation.reverse();
});
// スキップ(アニメーション終了状態まで飛ばす)
skip.addEventListener("click", function () {
animation.finish();
});
// アニメーションの終了を監視(play() reverse() finish()は完了時にresolveされたpromiseを返す)
async function observeFinish(animation) {
return animation.finished;
}
async function finished() {
await observeFinish(animation);
// アニメーション終了後に実行したい処理を記述
finish.style.backgroundColor = "yellow";
}
// アニメーション終了後に実行したい処理を実行
finished();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment