Front-end animation implementation

1. Basic principles of animation

1. What is animation

Animation is the process of creating the illusion of motion and change by arranging batches of images in rapid succession with very little difference

In the ancient people began to have animation long ago, the following is five thousand years ago the ancients of the painting, with today’s technology to put this several pieces of continuous splice together can see a movement 🐏

For example, we often say “frame”. Generally, movies and TV have 24 frames per second, that is, there are 24 pictures per second. Because the difference of adjacent pictures is very small and the playback speed is fast, our visual residual effect will present a continuous picture.

2. History of animation

The very beginning of computer animation was continuous images, using the GIF format to store images as moving images. Later, with the rise of Flash, relatively complex and better effects of animation can be made. Flash animation became popular all over the world, and animation on web pages was basically contracted by Flash.

It wasn’t until Apple’s mobile devices came along that The company decided that flash would take up too much memory and processor power to play, which would cause damage to fragile mobile devices. As Apple’s market share grew, flash was abandoned around the world.

Another reason for the decline of Flash animation is that Adobe handed over the operation of Flash to domestic manufacturers, who failed to make progress. Flash optimization was poor, and it was a pile of advertising, which gradually drove them out of the market

After flash exit, there is no better substitute for a time, we have to use GIF pictures instead of animation, until the advent of CSS3, web pages can use CSS code to write animation, GIF was slowly replaced

 

3. Computer animation principle

Computer Graphics:

The foundation of computer vision, covering the mathematical construction of points, lines, surfaces, volumes and fields.

  1. Input, storage and compression of geometric and graphic data
  2. Describe texture, curve, light and shadow algorithms
  3. Object graphics data output (graphics interface, animation technology), hardware and graphics interaction technology
  4. Technical standards for graphics development software

Computer animation:

A branch of computer graphics, including 2D and 3D animation

No matter how simple an animation is, you always need to define two basic states, the start state and the end state. Without these two states, there is no way to define interpolation states to fill in the gaps between them.

For example: the top ball starts on the left and ends on the right, so how does the middle move? We can interpolate this. You can make it go straight, you can make it curve, you can even walk out of the picture for a minute and fall off. But if there’s only any one state, and we don’t know where the ball ends and where it starts, there’s no way to define its state.

  • Frame: A sequence of images, each of which is a frame
  • 1. A measure of the number of frames in a given period of time. The usual unit of measurement is frame per second.
  • Frame rate and the human eye: 10-12 frames per second are considered continuous, a phenomenon known as visual persistence. For some computer animations and games, it will be obvious that they are stuck under 30FPS, but on mainstream screens, the graphics output at 60FPS is much smoother.

On the phone it’s called refresh rate. For example, the current maximum refresh rate is 120Hz, which means the screen refreshes 120 times per second, and the animation is very smooth

In the ball example above, we fill in the frames between the ball’s two position states to form a continuous animation, which is called tween animation

  • Tween animation (keyframe animation)

    In traditional animation, the main artist draws key frames (such as the middle frame of the key action of the character, from raising hand to dropping hand) and delivers them to the clearing department, and the tween animator of the clearing department adds key frames for delivery (the action state from raising hand to dropping hand). (In rendering a web page, the role of the tween animator is played by the browser, e.g., KeyFrame, Transition)

  • Frame By Frame animation

    In the literal sense of the word, every frame is hand-drawn. (Such as Sprite image implemented by Steps)

Two. The classification of front-end animation

Front-end animation can be roughly divided into three categories. A new animation feature of CSS3 is SVG, which draws elements, and JS animation, which uses JS code to obtain DOM elements and change the state and position of DOM elements to form animation

1.CSS

CSS shape changes ———— Transform API

Only elements located by the box model can be transformed. As a rule of thumb, the element is positioned by the box model if it has a Dispaly: block.Copy the code
<transform-function> == 
<matrix()> | 
<translate()> | 
<translateX()> | 
<translateY()> | 
<scale()> | 
<scaleX()> | 
<scaleY()> | 
<rotate()> | 
<skew()> | 
<skewX()> | 
<skewY()> | 
<matrix3d()> | 
<translate3d()> | 
<translateZ()> | 
<scale3d()> | 
<scaleZ() | 
<rotate3d()> | 
<rotateX()> | 
<rotateY()> | 
<rotateZ()> | 
<perspective> 
Copy the code

Translate (mobile)

The transformation consists of two dimensional vectors. Its coordinates define how much the element has moved in each direction

Transform: Translate (200px) /* Move 200px in each direction */ transform: Translate (50%) /* 50% of the object moving in each direction */ /* The units in each direction can be customized, and the units in each direction are calculated independently of each other */ transform: Translate (100px,200px) /* X 100px Y 200px */ transform: translate(100px,50%) /* X 100px Y 50% of the length of the object in y */ transform: Translate (30%,200px) /* 30% of the length of the object in x direction 200px */ in Y directionCopy the code

Scale (zoom)

/* Shrink by 50% along the X-axis with only one argument */
transform:scale(0.5/* With two parameters, the first is in the x direction, and the second is in the y direction50%Zoom in on the y axis2Times * / transform:scale(0.5.2)
Copy the code

The rotate (rotation)

The center of rotation defaults to center, the center of the object

Transform: Rotate (30deg) /* Rotate 30 degrees clockwise */Copy the code

Skew

transform:skew(30deg,10deg)
Copy the code

The parameter represents the tilt Angle, in deg

A parameter: indicates the horizontal tilt Angle

With two parameters: the first parameter represents the horizontal tilt Angle, and the second parameter represents the vertical tilt Angle

The first thing to note is that the default remote point of skew transform-Origin is the center point of the object

CSS implementation of Tween (Transform API, Keyframe)

Transition API (Transition Animation)

Triggered when the DOM has finished loading or the class has changed

Div {the transition: <property> <duration> <timing-function> <delay>} /* transition-property Specifies which CSS properties are used for transition-duration specifies the transition duration Transition-timing -function Specifies a function that defines how the value of an attribute changes. Transition-delay specifies the delay between when the attribute changes and when the transition begins. */Copy the code

Keyframe implements animation

Keyframe@KeyFrame at-rule Controls intermediate steps in A CSS animation sequence by styling keyframes (or waypoints) in the animation sequence. In contrast to Transition, the keyframe controls the intermediate steps of an animation sequence

@keyframes slidein { from { transform: translateX(0%) } to { transform: | | | | | | | | | | | | | | | | | left:0; } 30% {top:50px} 68%,72% {left:50px} 100% {top:100px; Left :100%}} /* More detail on the object transformation Settings, specify the keyframe states at 30%, 68%, 72% outside of the start and end */Copy the code

Once you’ve created the state of the keyframe, you need to animate the object

# Alice {animarion: Identifier infinite 3s linearCopy the code

CSS implements frame-by-frame animation

The API figure above you can see, there is a two step parameters, on behalf of the realization of this animation in a few steps, a number 1 is one step, start the meaning is behind the end state as the initial state, in the upper part can be seen from the above, the end state of small black spots in the upper right, because only one step, the initial state is an end state, Sync before the animation starts. In the upper right part of the figure, you can see that the end state of the ball is in the upper right and the start state is in the lower left. The start state does not change until the animation starts, and the end state comes one step after the start. And so on

.sprite { position:absolute; height:500px; width:420px; The transform: scale (0.4); Animation: 0.9 s run - h steps (14) infinite; background-image:url(test.png); } @keyframe run-h { to{ background-position:-5888px 0 } }Copy the code

This is a Sprite, and a Sprite is a very large image with lots of sub-frames, and we control the movement of the Sprite in the view window to show different areas

The above code is to divide this very long Sprite map into 14 steps for displacement, 0.9s to complete displacement, loop play, will appear above the dynamic elf

conclusion

Advantages: simple, efficient, declarative, independent of the main thread, partially using hardware acceleration (GPU), simple control of the KeyFrame Animation playback pause

Disadvantages: animation content cannot be dynamically modified or defined, different animations cannot be synchronized, multiple calls cannot be stacked on top of each other

Application scenario: simple H5 campaign/publicity page

Recommended libraries: animation.css shake.css, etc

2.SVG

SVG is a vector graphic description language based on XML. It can cooperate well with CSS and JS. There are usually three ways to realize SVG animation: SMIL, JS and CSS

SMIL

Synchronzed Multimedia Integration Language (SMIL)

<svg width="320" height="320" xmlns="http://www.w3.org/2000/svg"> <g> <text font-family="microsoft yahei" Font ="120" y="160" x="160"> </text> <animateTransform attributeName="transform" brgin="10s" type="rotate" from="0 160 160" repeatCount="indefinete" /> </g> </svg>Copy the code

Compatibility is not very good, let’s not discuss this method

JS

Using JS to manipulate SVG animations, there are already a number of libraries available online. For example, the old snap. SVG and Animos. js allow us to make SVG animations quickly. Of course, in addition to these libraries, HTML itself has a native Web Animation implementation. Using Web Animation also allows us to make animations easily and quickly

Codepen. IO /jiangxiang/…

Codepen. IO /jiangxiang/…

Js stroke principle

Stroke - dashoffset, stroke - used dasharray implementation effect of the stroke - dasharray: < length > | < percentage > (need to populate the path) Stroke - dashoffset: < length > | < percentage > (dash pattern starting position offset)Copy the code

Path Path -d property (Path description)

* Upper and lower case letters follow the absolute coordinates x, y, and lower case letters are the relative coordinates dx, dy

M/ M draws the starting point

L/ L Draws a line segment

C/ C is to draw the Bezier curve

Z/ Z connects the current point with the starting point in a straight line

Calculate the length of the path – path.getTotallLength()

Calculate the coordinates of a point on path – path.getPointatLength (lengthNumber)

Example: codepen. IO/jiangxiang /…

CSS

CSS mainly uses animation, Transform and Transition to realize animation, which is simpler and more convenient than JS

conclusion

Advantages: Animation through vector elements, different screens can get better clarity. Can achieve some special effects: stroke, deformation, ink diffusion and so on

Disadvantages: The usage mode is complex, and excessive use may cause performance problems

3. JS animation

JS can implement complex animation, and can also operate on the Canvas animation API to draw

conclusion

Advantages:

  • Flexible use, also in the definition of an animation keyframe sequence, can adjust a number of parameters according to different conditions (JS animation function) to change the animation mode. (CSS can have a lot of code redundancy)
  • Compared with THE CSS keyframe granularity is coarser, CSS itself time function is limited, this JS can make up
  • CSS is difficult to do more than two state transitions (either using keyframes, or requiring multiple animation delay triggers, and then trying to looping or pausing the animation in reverse order, etc.)

Disadvantages:

  • When using JS runtime, the tuning aspect is not as simple as CSS, CSS tuning method is fixed
  • For browsers with poor performance and compatibility, CSS can be elegantly degraded, while JS requires additional code compatibility

Three. Realize front-end animation

JS animation function encapsulation

Function to choose

requestAnimationFrame vs setTimeout vs srtInterval

JavaScript animations should be done through requestAnimationFrame, a built-in method that allows the callback function to be set to run when the browser is ready to draw. This passes quickly, but the exact time depends on the browser

When the page is in the background, there is no redrawing at all, so the callback does not run: the animation is paused and does not consume resources

function animate({timing,draw,duration}){
    let start = performance.now()
    
    requestAnimationFrame(function animate(time){
        //timeFraction is a time segment. The value is between 0 and 1
        let timeFraction = (time - start) / duration
        if(timeFraction > 1 ) timeFraction = 1
        
        // Calculate the current animation state
        let progress = timing(timeFraction)
        
        draw(progress)   / / to draw
        
        if(timeFraction < 1 ){
            requestAnimationFrame(animate)
        }
    }) 
    
}
Copy the code

TimeFraction represents the state of animation completion. If the value is greater than 1, the animation is completed. If the value is less than 1, a timing function is given

The difference between performance.now() and other time functions such as date.now ()

Perform.now () increments at a constant rate, accurate to microseconds, and is not easily tampered with. Gets a time score from 0 to 1 that returns the animation progress, usually 0-1

Duration Total animation time in milliseconds

Draw A function that draws an animation

Simple animation

Animation can be simply likened to speed * time

Uniform motion

Const draw = (progress)=>{draw.style. transform = 'translate(${progress}px,0)'} timing(timeFraction){ return timeFraction * 500 }, draw })Copy the code

As shown above, when time is fixed and speed is constant, it is uniform motion

Gravity (uniformly accelerated motion)

As we can see above, gravity is a uniformly accelerated linear motion, the acceleration is constant, the speed is getting faster and faster

Const draw = (progress) =>{train. Style. transform = 'translate(0,${500 *(progress-1)}px)'} duration:1000, timing(timeFraction){ return timeFraction ** 2 }, draw, })Copy the code

Friction (uniform deceleration)

In contrast to gravity, frictional motion is uniform deceleration motion, constant friction, constant deceleration, and less and less speed

Transform = 'translate(0,${500 *(progress-1)}px)'} // Constant motion along the x axis Animate ({duration:1000, timing(timeFraction){return timeFraction *(2-timefraction)}, draw,})Copy the code

Flat throw (x axis uniform speed, Y axis acceleration)

A flat throw can be decomposed into a uniform motion in the horizontal direction, plus a gravitational motion in the vertical direction

Const draw = (progress) =>{train. Style. transform = 'translate(${500 *(progress)}px, const draw = (progress) =>{train. ${500 *(progress-1)}px) '} animate({duration:1000, timing(timeFraction){return {x: timeFraction, y: timeFraction ** 2 }, }, draw, })Copy the code

Rotation + flat throw (x axis uniform speed, Y axis acceleration, rotation uniform speed)

Const draw = (progress) =>{train. Style. transform = 'translate(${500 *(progress)}px, const draw = (progress) =>{train. Rotate (${2000 * progress.rotate}deg) rotate(${2000 * progress.rotate}deg) rotate({duration:1000, Return {x: timeFraction, y: timeFraction ** 2, rotate:timeFraction,},}, draw,}) return {x: timeFraction, y: timeFraction ** 2, rotate:timeFraction,},}, draw,}Copy the code

Bow drawing (X-axis uniform speed + Y-axis initial speed negative uniform acceleration)

Through the motion curve above, we can also be analogous to the upward throw motion, which has an extra uniform deceleration motion in the vertical direction compared to the flat throw

const back  = (x,timeFraction) =>{
    return Math.pow(timeFraction,2) * ((x +1) * timeFraction - x)
}
const draw = (progress) =>{
    train.style.transform = `translate( ${ 200 * progress.x }px , ${ - 500 * progress.y }px )`
}
animate({
    duration:1000,
    timing(timeFraction){
        return {
            x:timeFraction,
            y:back(2,timeFraction),
        }
    },
    draw
})
Copy the code

Bounce a ball

Use the slow function implementation

Use the slow function implementation

Const bounce = (timeFraction) =>{if(timeFraction < 1/2.75) {return 7.5625 * timeFraction * timeFraction}else If (timeFraction < 2/2.75){return 7.5625 * (timeFraction - = 1.5/2.75) * timeFraction + 0.75}else if(amount < 2.5 / 2.75){return 7.5625 * (timeFraction - = 2.5/2.75) * timeFraction + 0.9375}else{return 7.5625 * (timeFraction - = 2.625/2.75) * timeFraction + 0.984375}} const draw = (progress)=>{style.transform = 'translate(${200 *) progress.x }px, ${200 * (progress.y - 1)}px)` } animate({ duration:1000, timing(timeFraction){ return { x:timeFraction, y:bounce(timeFraction), } }, draw })Copy the code

Automatic attenuation implementation

(async function(){let damping = 0.7, duration = 1000, height = 300 while(height > 1){ const down = (progress) =>{ train.style.transform = `translate(0,${height * (progress - 1)}px)` } await animate({ duration:duration, timing(timeFraction){ return timeFraction ** 2 }, draw:down }) height *= damping ** 2 duration *= damping const up = (progress) =>{ train.style.transform = `translate(0,${- height * progress}px)` } await animate({ duration:duration, timing(timeFraction){ return timeFraction * (2 - timeFraction) }, draw: up }) } })Copy the code

four

. Relevant practices

Animation resources

Examples of animation code:

codepen.com

codesandbox.com

Design website:

dribbble.com

Animation tool

2D:Animate CC 、After Effects

3D:Cinema 4D, Blender, Autodesk Maya

SVG

– snap.svg a JavaScript library for modern SVG graphics

– svg.js lightweight library for manipulating and animating Svg

JS

-GSAP JavaScript animation library

-TweenJS is a simple but powerful JavaScript tween/animation library. Part of the CreateJS library suite

-Velocity Accelerated JavaScript animation

CSS

-Animate. CSS Cross-browser library for CSS animations. As easy to use as a simple thing

canvas

-EaselJS is a library for building high performance interactive 2D content in HTML5

-Fabric.js JavaScript canvas library that supports animation

– paper.js Vector graphic script for Swiss Army Knife

-Scripttographer ports to JavaScript and browsers using HTML5 Canvas

Pixijs uses the fastest and most flexible 2D WebGL renderer to create beautiful digital content

Work practice

Animation Frames -> Code & Design File -> Code conversion

– Need a complete front-end development

Use an already packaged animation library and choose between development costs and experience

– The design is not very empty

Sharpness, picture format can be specified, animation as far as possible to give the machine or similar case reference

Request Sprite resources, resources, etc. Need help compression

– Sufficient design resources

Required design to export Lottie format files

Lottie is a library for Android, iOS, Web, and Windows that uses Bodymovin to parse AE animations and export JSON files that can render animations on mobile and Web

Optimization of animation

Performance optimization

See this article for more information on page rendering performance

Why is CSS animation more efficient than JavaScript controlled animation?

This article details the performance problems of CSS in rendering

In practice, one of the easiest things to do is not to use display: None at the start of the animation, because it will trigger Layout and Paint. Switching the class name is a good way to do this

Translate values instead of top/left/right/bottom, scale values instead of width/height,opacity values instead of display/visibility, etc

Animation optimization

CSS3 hardware acceleration, also known as GPU acceleration, is an optimization scheme that uses GPU to render and reduce CPU operations. Since CSS properties such as Transform in the GPU do not trigger Repaint, the performance of web pages can be greatly improved.

The following properties in CSS can trigger hardware acceleration:

  1. transform
  2. opacity
  3. filter
  4. Will-change

If you have elements that do not need the above attributes but need to trigger hardware acceleration, you can use a few tricks to induce the browser to turn on hardware acceleration

Algorithm to optimize

– Linear functions instead of real calculations

– Geometric model optimization

– Collision detection optimization

Memory/cache optimization

Off-screen drawing