It’s not enough to only use plug-ins. These front-end animation technologies are also worth collecting-JavaScript (Part 2)

Table of contents

foreword

introduce

basic use

Keyframe

Declaration of the three types of KeyframeEffect

keyframes

options

animation object

Global Animation class

animate function in the label

Summarize

Relevant code:


foreword

Then the above is introduced. In the last article, we have a detailed understanding of JS native animation and Bezier curves. Based on timers or animation frames, we can realize the animation and easing of elements. This article will share the functions in the browser. Powerful Animations API, friends who are interested, please read on

introduce

Web Animations API (WAAPI for short) became part of the Web standard in 2016. Its functions are much richer than the animations mentioned before . Its core concept is the timeline and animation effects. It provides a powerful set of methods and properties for defining, manipulating, and managing animation effects.

Timeline (Timeline) is one of the core concepts in WAAPI. It acts like a global clock that manages and coordinates all running animations. Through the timeline, developers can control animation playback, pause, reset and other operations.

An Animation Effect refers to a transition or change to be applied to an animation target. WAAPI provides various types of animation effects, such as translation, scale, and rotate. Developers can use these effects to create various animation effects.

basic use

Keyframe

Remember CSS keyframes from earlier ? Use from to or percentage to define the effect of the animation stage, use the KeyframeEffect class in JS to create keyframe animation

const box = document.querySelector(".box")
const keyframes = [
    { left: 0 },
    { left: '100px' }
];
const keyframe = new KeyframeEffect(box, keyframes, 1000);

In the above code, the KeyframeEffect class receives three parameters: the first is the target label, the second is the key frame, and the third is the animation time

Declaration of the three types of KeyframeEffect

  1. KeyframeEffect(keyframeEffect): copy keyframe configuration
  2. KeyframeEffect(element, keyframes, duration): generate a new animation on the label element, the keyframe is keyframes, and lasts for duration milliseconds
  3. KeyframeEffect(element, keyframes, options): Generate a new animation on the label element, the keyframe is keyframes, and the animation configuration options

keyframes

There are two ways to write keyframes, namely the way of array and the way of writing style objects

  • array
const keyframes = [
    { left: 0, top: "50px" },
    { left: '100px', top: "100px" },
    { top: "150px" }
];
  • object
const keyframes = {
    left: [0, '100px', '100px'], top: ["50px", "100px", "150px"]
}

options

The third parameter type of KeyframeEffect is a number or options configuration item, the number represents the animation duration, and options has the following properties:

  1. delay: The delay before the animation starts, in milliseconds, the default value is 0. Corresponding to the animation-delay of css
  2. direction: The playback direction of the animation, which can be "normal" (normal playback), "reverse" (reverse playback), "alternate" (alternate playback) or "alternate-reverse" (alternate reverse playback). The default value is "normal". Corresponding to the animation-direction of css
  3. duration: The duration of the animation, in milliseconds, the default value is 0. Corresponding to the animation-duration of css
  4. easing: The easing function of the animation, you can use CSS easing functions, such as "linear", "ease", "ease-in", etc., or a custom easing function. The default value is "linear". Corresponding to the animation-timing-function of css
  5. endDelay: The delay time after the animation ends, in milliseconds, the default value is 0.
  6. fill: The behavior of the animation during the inactive time period, which can be none (by default, no effect will be retained after the animation ends), forwards (the effect of the last frame will be maintained after the animation ends), or backwards (the effect of the first frame will be applied before the animation starts Effect). It can also be both, which means that the effects of forwards and backwards are applied at the same time. animation-fill-mode corresponding to css
  7. iterationStart: The iteration start position of the animation, expressed as a decimal (for example, 0.5 means to iterate from the middle of the animation), and the default value is 0.
  8. iterations: The number of iterations of the animation, which can be a positive integer or Infinity (infinite loop), the default value is 1. Corresponding to animation-iteration-count of css
  9. keyframes: The keyframes of the animation, which can be a keyframe rule object or an array of keyframes.
  10. playbackRate: A property used to control the playback rate of the animation. It can be used to speed up or slow down the playback speed of the animation.
  11. composite (CompositeOperation): The composite behavior of the animation. Can be replace or add. The default is replace. replace means that the animation will overwrite the current value of the target property, and add means that the animation will be superimposed with the current value of the target property.
  12. iterationComposite(IterationCompositeOperation): Value composition behavior between animation iterations. Can be replace or accumulate. The default is replace. replace means that the value of the animation will replace the current value of the target property at each iteration, and accumulate means that the value of the animation will be accumulated to the current value of the target property at each iteration.
  13. pseudoElement: The pseudo-element to which the animation is applied. Can be a string indicating the name of the pseudo-element, such as before or after, or it can be null to apply to the main element rather than the pseudo-element.

example

<!DOCTYPE html>
<html lang="CH">

<head>
    <meta charset="UTF-8" />
    <title>webAnimationsAPI</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .box {
            width: 200px;
            height: 200px;
            top: 50px;
            position: absolute;
            background: lightblue;
        }

        .box::after {
            width: 100px;
            height: 100px;
            content: "";
            left: 50px;
            position: absolute;
            background: lightcoral;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button onclick="playHandler()">开始</button>
    <script>
        const box = document.querySelector(".box")
        const keyframes = [
            { transform: "rotate(0)" },
            { transform: "rotate(180deg)" },
            { transform: "rotate(360deg)" },
        ];
        const options = {
            delay: 500,// 延迟500毫秒开始动画
            duration: 1000,// 持续时间为1000毫秒
            easing: 'ease-in-out',// 缓动函数为ease-in-out
            iterations: Infinity,// 迭代3次
            direction: 'alternate',// 交替播放
            endDelay: 1000,// 延迟1000毫秒开始动画
            fill: "forwards",// 结束后保持最后一帧的效果
            iterationStart: .2,// 从动画的20%位置开始迭代
            composite: 'add',//使用add合成行为
            keyframes: keyframes,//指定关键帧
            playbackRate: 2.0,//播放速率为2倍
            iterationComposite: 'accumulate',//使用accumulate合成行为
            pseudoElement: '::after'//应用于after伪元素
        }
        const keyframe = new KeyframeEffect(box, keyframes, options);
        function playHandler() {
            const animation = new Animation(keyframe, document.timeline);
            animation.play();
        }
    </script>
</body>

</html>

Effect

animation object

Global Animation class

After creating the keyframes of the animation, we can use the global Animation class to create animations in the form of the above keyframes

const box = document.querySelector(".box")
const keyframes = [
    { left: 0, top: "50px" },
    { left: '100px', top: "100px" },
    { top: "150px" }
];
const keyframe = new KeyframeEffect(box, keyframes, 1000);
function playPauseHandler() {
    const animation = new Animation(keyframe);
    animation.play();
}

Use new Animation(keyframe) to create a new animation, and then use the play function to activate the animation

The effect is as follows

There are two parameters of the Animation constructor: the keyframe object AnimationEffect and the timeline AnimationTimeline. The former is the KeyframeEffect mentioned above. AnimationTimeline can generally be described by document.timeline

const animation = new Animation(keyframe, document.timeline);

There are many properties and methods in the animation object

Attributes

  • id: Returns the unique identifier for the animation.
  • startTime: The timestamp when the animation started.
  • currentTime: The time of the current animation in milliseconds.
  • playbackRate: The playback rate of the animation, the default value is 1.
  • effect: the effect of the animation, a KeyframeEffect object.
  • timeline: the timeline used by animation, AnimationTimeline object.
  • playState: The current playback state of the animation, possible values ​​are "idle", "pending", "running", "paused", "finished".
  • pending: the waiting state of the animation, that is, whether the animation is in the pending state.

method

  • play(): Play animation.
  • pause(): Pause the animation.
  • cancel(): Cancel the animation.
  • finish(): Finish the animation.
  • reverse(): Reverses the playback direction of the animation.
  • updatePlaybackRate(playbackRate): Update the playback rate of the animation.
  • addEventListener(type, listener): Add event listener on animation. Such as: finish (complete), cancel (cancel) and pause (pause), etc.
  • removeEventListener(type, listener): Removes the event listener from the animation.
  • oncancel: An event handler that is executed when the animation is canceled.
  • onfinish: An event handler that is executed when the animation completes.

Example of use

<!DOCTYPE html>
<html lang="CH">

<head>
    <meta charset="UTF-8" />
    <title>webAnimationsAPI</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .box {
            width: 200px;
            height: 200px;
            top: 50px;
            position: absolute;
            background: lightblue;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button onclick="playHandler()">开始</button>
    <button onclick="pauseHandler()">暂停</button>
    <button onclick="cancelHandler()">取消、重置</button>
    <button onclick="reverseHandler()">反向运行</button>
    <button onclick="finishHandler()">完成动画</button>
    <button onclick="playbackRateHandler()">更新动画速率</button>
    <button onclick="playStateHandler()">获取状态</button>
    <button onclick="currentTimeHandler()">获取时间轴位置</button>
    <script>
        const box = document.querySelector(".box")
        const keyframes = [
            { left: 0 },
            { left: '300px' },
        ];
        const keyframe = new KeyframeEffect(box, keyframes, {
            duration: 1000,
            iterations: Infinity,
            direction: 'alternate',
            fill: "forwards",
        });
        const animation = new Animation(keyframe, document.timeline);
        animation.addEventListener("finish", console.info)
        animation.addEventListener("cancel", console.info)
        animation.addEventListener("remove", console.info)
        function playHandler() {
            animation.play();
        }
        function pauseHandler() {
            animation.pause();
        }
        function cancelHandler() {
            animation.cancel();
        }
        function reverseHandler() {
            animation.reverse();
        }
        function finishHandler() {
            animation.finish();// 当iterations等于infinity时无法触发完成
        }

        function playStateHandler() {
            console.log(animation.playState);
        }
        function playbackRateHandler() {
            animation.updatePlaybackRate(2)
        }
        function currentTimeHandler() {
            console.log(animation.currentTime);
        }
    </script>
</body>

</html>

The effect is as follows

animate function in the label

The global Element tag object inherits from the Animatable interface

This interface describes two methods: animate adds animation to the current label and getAnimations gets all animations of the current label

interface Animatable {
    animate(keyframes: Keyframe[] | PropertyIndexedKeyframes | null, options?: number | KeyframeAnimationOptions): Animation;
    getAnimations(options?: GetAnimationsOptions): Animation[];
}

Usage is similar to KeyframeEffect+Animation

<!DOCTYPE html>
<html lang="CH">

<head>
    <meta charset="UTF-8" />
    <title>webAnimationsAPI</title>
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            position: relative;
        }

        .box {
            width: 200px;
            height: 200px;
            top: 50px;
            position: absolute;
            background: lightblue;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <button onclick="playHandler()">开始</button>
    <button onclick="pauseHandler()">暂停</button>
    <script>
        const box = document.querySelector(".box")
        const keyframes = [
            { left: 0 },
            { left: '300px' },
        ];
        const opts = {
            duration: 1000,
            iterations: Infinity,
            direction: 'alternate',
            fill: "forwards",
        }
        const animation = box.animate(keyframes, opts)
        function playHandler() {
            animation.play();
        }
        function pauseHandler() {
            animation.pause();
        }
    </script>
</body>

</html>

Summarize

This article shares with you the newly launched JS native animation WAAPI in 2016. The animation object created in this way is very powerful. Among them, we can use KeyframeEffect to set the style of the keyframe of the label, and run the animation of the label through the Animation object. Compared with the previous two articles about animation, WAAPI is powerful, but compatibility issues need to be considered when using it.

Well, the above is the whole content of the article. I hope the content of the article is helpful to you. If you think the article is good, I hope you can support the blogger three times. Thank you~

Relevant code:

myCode: some small cases or projects based on js - Gitee.com

Guess you like

Origin blog.csdn.net/time_____/article/details/131139440