This is the 20th day of my participation in the Genwen Challenge

Relearn JavaScript in a series of articles…

Talking about animation we first think of CSS3, JS animation, which in the realization of infinite loop is better? Here summarizes the knowledge points involved, as well as the realization of the basic infinite loop animation, as well as the advantages and disadvantages of analysis.

The following HTML elements, the implementation of elements from left to right, and then from right to left infinite loop animation.

<! DOCTYPE html> <html> <head> <meta charset=" utf-8"> <style> #box { width: 100px; height: 100px; background: red; position: relative; } </style> </head> <body> <div id="box"></div> </body> </html>Copy the code

CSS 3 animation

animation

Look at the CSS3 Animation properties.

animation:

name

duration

timing-function

delay

iteration-count

direction

fill-mode

play-state;

  1. Animation-name: Specifies the name of the keyframe to bind to the selector, that is, the name specified by the @keyframes animation, or None.

  2. Animation-duration: Defines how many seconds or milliseconds it takes for an animation to complete a cycle.

  3. Animation-timing-function: Specifies how the animation will complete a cycle by defining the speed curve. (Speed curve: Defines how long it takes for an animation to change from one SET of CSS styles to another)

    1. Predefined speed curve

    linear | ease | ease-in | ease-out | ease-in-out

    1. Cubic Bezier curves

    Cubic – Bezier (n,n,n,n), the value ranges from 0 to 1

  4. Animation-delay: Define when the animation starts

  5. Animation-rorod-count: defines how many times the animation should be played. If it is infinite, it should be played indefinitely. If it is a number, it should be played several times.

  6. Animation-direction: indicates whether the animation is played alternately and reverse-direction. If the animation is played only once, this property does not take effect. If the value is alternate, odd times are played normally, and even times are played backward.

  7. Animation-fill-mode: Style to be applied to an element when the animation is not playing (when the animation is finished, or when the animation has a delay before it starts playing).

  8. Animation – play – state: specifies whether the animation is running or suspended, value is paused | running.

@keyframes

The meaning of keyframe defines the state of the animation at different stages. It is usually divided into three states: 0%, 50% and 100%.

Related theoretical knowledge, look at the following code implementation:

<style type="text/css">
   #box {
     animation: loopanimation 4s infinite alternate;
     -webkit-animation: loopanimation 4s infinite alternate;
     -moz-animation: loopanimation 4s infinite alternate;
     -o-animation: loopanimation 4s infinite alternate;
     -ms-animation: loopanimation 4s infinite alternate;
   } 
   @keyframes loopanimation {
     0% {
        left: 0px;
     }
     50% {
        left: 100px;
     }
     100% {
        left: 0px;
     }
   } 
</style>
Copy the code

The advantages and disadvantages

Advantages:

The browser can optimize the animation as follows:

  1. Browsers use a mechanism similar to requestAnimationFrame, which is described in the JS animation below.

  2. Improve animation performance with GUP (force hardware acceleration)

Disadvantages:

  1. CSS3 animation is difficult to control. There is no way to attach events to the callback function, it can only pause, and it cannot look for a specific point in time in the animation, reverse the animation, or change the time scale.

  2. Not conducive to writing complex animation, easy to cause lengthy code.

JS animation

Write an animation function:

Let animationFun = function(){let box = document.getelementById ('box') let pos = 0 // start position let end = 500 // end position let Return function animate(box, pos, end, step, toRight){ if(toRight){ if(pos<=end ){ pos+=step toRight = pos>=end? false:true } }else{ pos-=step toRight = pos<=0? true:false } box.style.left = pos+'px' } }Copy the code

setInterval

The setInterval loops at 1000/60, since most browsers render at 60 frames /s

let animate = animationFun()
let timer = setInterval(function(){
    animate()
},1000/60) 
Copy the code

requestAnimationFrame

RequestAnimationFrame is an animation framework with the following advantages:

  1. All DOM operations in each frame are grouped together in a single redraw or reflow, and the redraw or reflow interval closely tracks the browser refresh rate, which is typically 60 frames per second.

  2. RequestAnimationFrame does not redraw or recycle hidden or invisible elements, which of course means less CPU, GPU, and memory usage.

let animate = animateFun()
function animloop() {
   animate();
   window.requestAnimationFrame(animloop);
}
animloop()
Copy the code

The advantages and disadvantages

Advantages:

  1. JS animation control ability is strong, you can start, pause, stop, cancel and other operations in the animation playback.

  2. JS animation can achieve more complex animation effects, such as: curve movement, impact flashing and so on.

  3. CSS3 has compatibility issues, while most JS have no compatibility issues.

Disadvantages:

  1. JavaScript runs in the main thread of the browser, and there are other JavaScript scripts, style calculations, layout, and drawing tasks that need to be run in the main thread. Interference with the main thread may block, resulting in frame loss.

  2. Code complexity is higher than CSS animation.

conclusion

One last question? Why are CSS3 animations smoother than JS animations?

The rendering thread is divided into the main thread and the synthesizer thread. If the CSS animation only changes the transform and opacity properties, the animation is completed directly in the synthesizer thread. JS animation, will be in the main thread, and then trigger the synthesizer thread for the next operation. If at this time JS thread to perform expensive tasks, the main thread is busy, will cause frame loss jam, at this time using CSS animation more smooth. Therefore, CSS3 animation is smoother than JS animation based on certain premises:

  1. JS is performing expensive tasks

  2. CSS animations do not trigger Layout or Paint.

    Because a redraw or rearrangement is triggered, the main thread is required to recalculate the Layer tree, and the animation blocks subsequent operations. Don’t trigger redraws rearrangement of the attributes are: transfrom | opacity | perspective – origin | perspective | backface – visibility

At this point, we use the animation example to achieve infinite loop, learning CSS3 animation and JS animation, as well as the advantages and disadvantages of the previous. In short, no intermediate process control is required, just simple state switching, select CSS animation. If you need complex animation, process control, etc., choose JS animation.