Big front-end development often encounter animation development, so what is animation? In physics, motion is to study the phenomenon that objects change in time dimension and space dimension, so animation is the same. Animation mainly studies two factors, time and space of moving objects.

Animation in Web front-end development

There are two ways to implement animation in Web front-end development. Either CSS or JS controls are used to animate.

CSS for animation

First, there are four CSS concepts: animation, Transition, Transform, and Translate

attribute meaning
Transition (Animation) It is used to set the style transition effect of elements, which has a similar effect with animation, but has a big difference in the application occasions
The transform (deformation) Used to set the rotation, displacement, and scaling of elements. It’s not directly related to setting the element’s animation, just like writing CSS properties
Translate (mobile) Used to set the position of the element, which is an attribute of transform
Animation Used to set the animation property of venom, which is a short term with six property values

Transition literally is the transition of an element from one value of attribute A to another value of attribute A. This is a state change, but a condition is required to trigger the transition, such as &:hover,&: Checked,&:focus, media query, or JS

#box {
    height: 100px;
    width: 100px;
    background: green;
    transition: transform 1s ease-in 1s;
}
#box:hover{The transform: the rotate (180 deg) scale (0.5, 0.5); transform: translateX(100px); Transform: translateY(100px) translateX(100px) scale(0.5, 0.5); } <div id="box"></div>
Copy the code

Analysis: add a transition animation to the div. The animation specifies the transform animation to trigger when the mouse moves up. So the transition animation is triggered when the mouse moves over and the transform property changes, and the transition animation is triggered when the mouse moves over and the transform changes. There are three transform Settings, and only the last one works, so the transition animation is generated when its property changes, and it requires a driving force to trigger the animation. So there are some disadvantages:

  1. Requires an event trigger that cannot happen automatically when the page loads
  2. Is a one-time occurrence that cannot be repeated unless triggered again
  3. Only the start and end states can be defined, not the intermediate states, so there is no rich animation space
  4. A transition rule defines only one property change, not multiple properties

Transition: property duration timing-function delay

attribute meaning
transition-property Specifies the name of the CSS property that sets the transition effect
transition-duration Specify the time required to complete the transition effect
transition-timing-function The speed curve specifying the speed effect
transition-delay Specifies when the animation starts

animation

Animation is generally an enhancement of transition, and is no longer limited by the timing of the trigger and the value of the animation’s properties.

.box {
    height: 100px;
    width: 100px;
    border: 15px solid black;
    animation: changebox 4s ease-in-out 1s 1 alternate running forwards;
}
.box:hover {
    animation-play-state: paused;
}
@keyframes changebox {
    10% {
        background: red;
    }
    50% {
        width: 80px;
    }
    70% {
        border: 15px solid yellow;
    }
    100% {
        width: 180px;
        height: 180px;
    }
}
<div class="box"></div>
Copy the code

animation: animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode

attribute meaning
animation-name Used to call the animation defined by @keyFrames, the same animation name defined by @KeyFrames
animation-duration Specifies the duration for which the element plays the animation
animation-timing-function The speed curve for the speed effect is the frequency of change in the time range for each small animation
animation-delay Defines the wait time before the animation is executed
animation-iteration-count Define the number of times an animation can be played.
animation-direction Set the animation playing direction: Normal (according to the time axis order), alternate (i.e., back and forth)
animation-play-state Control the playback state of elements: RUNNING, paused
animation-fill-mode Controls the style of the element after the animation ends, with four values: None (back to the state before animation), forwards (elements stay at the end of animation), backwords (animation goes back to the first frame), and BOTH (rotated application of forwards and backwords depending on animation-direction Rules). Be careful not to conflict with rotund-count

Conclusion: Single animation effect, simple by transtion implementation, complex by animation implementation. After animation, there are many CSS libraries on the market. I recommend using animate. CSS

JS implementation of animation

SetTimeout and setInterval immediately come to mind when writing animation with JS. However, a better animation experience is to keep 60fps. The above two apis are not very punctual because they are affected by runloop. JS has a requestAnimationFrame API to keep animations at 60fps. The essence of JS animation implementation is to control the changes of elements in time and space.

If you want to create a uniform linear animation, move a DIV 500px horizontally from right to right in 3 seconds. So how to do that, let’s solve it from the physics problem.

Total time: 3s Total displacement: 500px So how much does it move per second 500px/3s let’s design a JS function. 4 parameters, property start value, property end value, animation execution time, callback function

Perform.now (); period = (now-start); perform.now (); Period /time is the percentage of progress of the time, and this percentage is multiplied by the total property value difference, which is the current property value. The result is then called in real time by the callback function (which specifies how the property value should be applied to the animation element).

** @param {Number} start * @param {Number} end * @param {Number} time * @param {Function} * @param {Function} timing timing */function animate(start, end, time, callback, timing = t => t) {
  letStartTime = performance.now() // Sets the start timestampletPeriod = end-start // Get the value difference // The function to execute before creating each framefunction loop() {liveAnimationFunction = requestAnimationFrame(loop) // Function to be executed before each frame is called const passTime = performance.now() - StartTime // obtains the difference between the current time and the startTimeletPer = passTime/time // Calculates the current percentageifCancelAnimationFrame (raf) // Stop animation} const pass = period * timing(per) // Callback (pass)}letLiveAnimationFunction = requestAnimationFrame(loop)function doMove(easing) {
  animate(0, 100, 1000, move.bind(null, document.querySelector(`#${easing}Box`)), EasingFunctions[easing])
}

function move(box, value) {
  box.style.transform = `translateX(${value}px)`
}
Copy the code

Native animations (iOS as an example)

In fact, the essence of animation is the study of changes in time and space of elements. This is true on the Web front end, and it’s true on the Native end, just with some API changes.

For example, take horizontal displacement as an example. Here’s the native code for iOS

// CABasicAnimation *positionAnimation = [CABasicAnimation animation]; / / specified animation path is horizontal X-axis positionAnimation. KeyPath = @"position.x"; / / specified displacement distance positionAnimation. ToValue = @ 1000; / / the following 2 lines of code to the location of the animation to stay at the end of the animation positionAnimation. FillMode = kCAFillModeForwards; / / (effect completely equivalent to the CSS animation - fill - mode attribute) positionAnimation. RemovedOnCompletion = NO; [self.animationView.layer addAnimation:positionAnimationforKey:nil];
Copy the code

Animation-fill-mode: animation-fill-mode: animation-fill-mode: animation-fill-mode: animation-fill-mode: animation-fill-mode None (back to the state before animation), forwards (elements stay at the end of animation), backwords (animation goes back to the first frame), and BOTH (rotated application of forwards and backwords depending on animation-direction Rule) is consistent with the fillMode attribute on native (iOS) terminals.

The following describes the fillMode option on iOS

/* `fillMode'Options. */ CA_EXTERN CAMediaTimingFillMode const kcafillmodeforward API_AVAILABLE(MacOS (10.5), ios(2.0), Tvos watchos (2.0), (9.0)); CA_EXTERN CAMediaTimingFillMode const kcafillmodeenol API_AVAILABLE(MACOS (10.5), ios(2.0), Watchos (2.0), Tvos (9.0)); CA_EXTERN CAMediaTimingFillMode const kCAFillModeBoth API_AVAILABLE(MacOS (10.5), ios(2.0), Watchos (2.0), TVOs (9.0)); CA_EXTERN CAMediaTimingFillMode const kCAFillModeRemoved API_AVAILABLE(MacOS (10.5), ios(2.0), Watchos (2.0), TVOs (9.0));Copy the code

It can be seen that the fillMode Web end is exactly the same as the native end.

For another example, it’s possible to draw a line, and there’s a view on both the Web side and the Native side, On the Web side it could be a div (height set to 1) or a Canvas implementation (Canvas gets the current context, draws the path, closes the path, fills the color). On the native end, also, open the drawing context, get the upper and lower objects, draw the path, color, and close the context.

So I won’t mention any other specific examples, but essentially all animations on the big front end do the same thing, so we need to deal with timing and location.