SVGアニメーション – Web Animations API を使う – KeyFrameEffectについて
KeyFrameEffectを試します。
基本構文
new KeyframeEffect(target, keyframes) new KeyframeEffect(target, keyframes, options) new KeyframeEffect(sourceKeyFrames)
サンプル
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
.animate_timeline_dom {
background-color: #cccccc;
width: 150px;
}
</style>
</head>
<body>
<input type="button" id="button_1" value="animate timline test">
<div class="animate_timeline_dom">Test DOM</div>
<script>
button_1.addEventListener('click', () => {
// DOM要素を取得
let animate_timeline_dom = document.querySelector(".animate_timeline_dom");
let keyframes_test = new KeyframeEffect(
animate_timeline_dom,
[
{transform: "translateX(0px)" },
{transform: "translateX(200px)"},
{transform: "translateY(100px)"},
{transform: "scale(2)" },
],
{ duration: 5000 },
);
let anim_test = new Animation(
keyframes_test,
document.timeline,
);
// アニメーションの再生
anim_test.play();
}, false);
</script>
</body>
</html>
サンプルでは、以下の箇所がKeyframeEffectを使用した定義です。
let keyframes_test = new KeyframeEffect(
animate_timeline_dom,
[
{transform: "translateX(0px)" },
{transform: "translateX(200px)"},
{transform: "translateY(100px)"},
{transform: "scale(2)" },
],
{ duration: 5000 },
);
targetは対象のDOM
keyframesは任意のアニメーションの内容を指定
optionsは任意のタイミングプロパティの内容を指定
前回の投稿で、animation の基本構文を書きました。
var animation = new Animation([effect][, timeline]);
この「effect」については、次の定義になります。
(MDNから抜粋) このアニメーションに関連付けられた AnimationEffect を取得または設定します。 これはふつう、 KeyframeEffect オブジェクトになります。
上記のサンプルで、アニメーションの定義を次のようにしていますが、
let anim_test = new Animation( keyframes_test, document.timeline, );
「keyframes_test」という記述が「new KeyframeEffect」したものであり、それが「new Animation([effect][, timeline]);」のeffectとして割り当てていると言えます。
new Animation の引数に new KeyframeEffect を記述する
new Animationの引数に直接new keyframeEffectを記述する例です。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>テストHTML</title>
<style>
.animate_timeline_dom {
background-color: #cccccc;
width: 150px;
}
</style>
</head>
<body>
<input type="button" id="button_1" value="animate timline test">
<div class="animate_timeline_dom">Test DOM</div>
<script>
button_1.addEventListener('click', () => {
let animate_timeline_dom = document.querySelector(".animate_timeline_dom");
let anim_test = new Animation(
new KeyframeEffect(
animate_timeline_dom,
[
{transform: "translateX(0px)" },
{transform: "translateX(200px)"},
{transform: "translateY(100px)"},
{transform: "scale(2)" },
],
{ duration: 5000 },
),
document.timeline,
);
// アニメーションの再生
anim_test.play();
}, false);
</script>
</body>
</html>