This is the 12th day of my participation in the August Text Challenge.More challenges in August

Writing in the front

As a front end, our mission is to present the best experience to users on the basis of meeting product requirements and realizing interaction design. While maintaining performance, we often add some dynamic effects to the page to enhance the expressive and interactive experience of the page. The author will take you through this article in-depth understanding of front-end animation ~

The fundamentals of animation

What is animation?

Animation is the process of creating the illusion of motion and change through the rapid and continuous arrangement of images with little difference between each other.

History of Animation

In fact, animation has been around for more than 5,000 years. Look at this painting found in Shahr Isukhta, Iran. This is one of the earliest examples of an artist trying to represent graphic motion through animation. Here are five pictures of goats walking up to a tree, climbing it, eating the leaves and coming down again.

Through modern animation technology, five images can be pieced together to play in a loop, forming an animation.

Principles of computer animation

Computational Graphics:

  1. The foundation of computer vision, covering the mathematical construction of points, lines, surfaces, volumes and fields.
  2. Input, storage and compression of geometric and graphic data.
  3. Describe texture, curve, light and shadow algorithms.
  4. Object graphics data output (graphics interface, animation technology), hardware and graphics interaction technology.
  5. 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 them, we would not be able to define interpolation states to fill in the gaps between the two.

Frame: A sequence of changing frames in which each frame is a frame. Frame rate: A measure of the number of frames in a given practice segment, usually measured in FPS. Frame rate and the human eye: Generally, 10-12 frames per second are considered to be coherent, a phenomenon known as visual persistence.

Tween animation (keyframe animation) : Traditional animation, the main artist draws key frames and delivers them to the finalizing department, and the tween animator of the finalizing department adds key frames for delivery. (By analogy, tween animation is done by the browser, such as KeyFrame,transiton)

Frame-by-frame animation: The term means that every frame of the film is completely hand-drawn frame by frame (e.g. steps to Sprite)

Front-end animation classification

CSS animations

CSS shape Changes – The Transform API can only Transform elements located by the box model.

Translate (mobile)

transform: translate(100px)
transform: translate(50%)
transform: translate(100px.200px)
Copy the code

Scale (zoom)

transform: scale(0.5)
transform: scale(0.5.2)
Copy the code

The Rotate (rotation)

transform: rotate(30deg)
Copy the code

Skew (oblique)

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

Parameter represents the tilt Angle. When the unit deG is a parameter, it represents the tilt Angle in the horizontal direction. With two parameters: the first parameter represents the horizontal tilt Angle, and the second parameter represents the vertical tilt Angle.

Transition API(Transition Animation)

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

  • transition-property

Specifies which CSS properties are used for transitions.

  • transition-duration

Specifies the duration of the transition

  • transition-function

Specify a function that defines how the property changes.

  • transition-delay

Specifies the delay, the length of time between when the property begins to change and when the transition begins to occur

Keframe implements animation:

The @keyframes at-rule controls intermediate steps and transitions in A CSS animation sequence by defining the style of the keyframes in the animation sequence.

@keyframes sliden{
    from {
        transform: translateX(0%)}to {
        transform: translateX(100%)}}Copy the code

CSS implements frame-by-frame animation

This is done through the STEP API

Advantages: simple, efficient, and independent of the main thread, it mainly adopts hardware acceleration (GPU) to control the play and pause of the KeyFrame Animation. Cons: Cannot dynamically modify or define animation content Different animations cannot be synchronized, multiple animations stacked on top of each other. Application scenario: simple H5 campaign/promotional page. Recommended libraries: animation. CSS, shake. CSS, etc.

SVG animation

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: Synchronous multimedia integration language

However, compatibility is not ideal and Internet Explorer 11 is not supported, which will not be discussed here. Using JS to manipulate SVG animations needless to say, there are already plenty of libraries on the web. For example, snap. SVG and animo.js allow us to make SVG animations quickly.

JS stroke principle

Stroke-dashoffset and stroke-Dasharray are used together to achieve stroke effect. Stroke – dasharray: < length > | < percentage > (path) need to fill the stroke – dasharray: < length > | > percentage > (dash pattern starting position offset)

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.

JS animation

JS can implement complex animations, or it can be controlled by manipulating the Canvas animation API.

How to choose

CSS advantages:

  • The browser optimizes CSS3 animations, resulting in a slight performance advantage for CSS3 animations (create a new layer to run the animations).
  • The code for CSS3 animation is relatively simple.

CSS faults:

  • Not flexible enough in animation controls.
  • Poor compatibility
  • Some animations cannot be implemented (parallax effect, scroll animation)

JS advantages:

  • flexible
  • Contrast with CSSkeyframeGranularity is coarser, CSS itself time function is limited, this JS can make up.
  • CSS is difficult to do more than two state transitions

JS faults:

  • When using JS runtime, debugging is not as easy as CSS, and CSS debugging is fixed.
  • For browsers with poor performance and compatibility, CSS can be elegantly degraded, while JS requires additional code compatibility.

Use CSS when you have small independent states for UI elements. Use JavaScript when you need a lot of control over your animation. SVG can be used in specific scenarios, and SVG changes can be manipulated using CSS or JS.

Animation to achieve

Js animation function encapsulation

JavaScript animations should be implemented with requestAnimationFrame. This built-in method allows you to set the callback function to run when the browser is ready to redraw. Usually this is quick, but the exact practice 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

tips:

  • The difference between performance. Now () and other time functions (date.now ()) is that performance.
  • Timing: Calculates the animation progress. Gets a time score from 0 to 1 and returns the animation progress, usually from 0 to 1.
  • Duration: Total animation time in milliseconds.
  • Draw: The function that draws the animation.

Work practice

Animation resources

Dribble: 2D: Animate CC, After Effects 3D: Cinema 4D, Blender, Autodesk Maya

SVG:

  • Snap.js – a JavaScript library for modern SVG graphics.
  • Svg.js — a lightweight library for manipulating and animating Svg.

JS:

  • GSAP — JavaScript animation library
  • TweenJS – a simple but powerful JavaScript tween/animation library. Part of the CreateJS library suite.
  • Velocity — Accelerated JavaScript animation.

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

Canvas:

  • EaselJS – EaselJS is a library for building high performance interactive 2D content in HTML5.
  • Fabric.js – a JavaScript canvas library that supports animation.
  • Paper.js – The Swiss Army Knife of vector graphics scripts.
  • Scriptgrapher — ports to JavaScript and browsers using HTML5 Canvas.
  • Pixijs – Create beautiful digital content using the fastest and most flexible 2D WebGL rendering.

Work practice

Animation Frames > Code & Design File > Code conversion

  • You need to develop your own front-end completely

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

  • The design students are not very free

Clarity, picture format can be specified, animation as far as possible to give a hint or similar case reference. Need to ask for genie resources, resources need to help compress.

  • 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

Make interface animation more natural

  • Performance point of view

The general process for page rendering is JS > CSS > Compute Style > Layout > Draw > Render layer merge.

Layout and Paint are the most time-consuming parts of the process, so avoid them as much as possible. An ideal rendering pipeline is one that has no layout and no drawing, just the merging of layers.

In practice, one of the easiest things to do is not to use dispaly: 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 replace top/left/right/bottom, scale values replace width/height,opacity values replace display/visiblity, and so on.

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 attributes in the CSS can trigger hardware acceleration:

  • transform
  • opacity
  • filter
  • 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

The last

⚽ this article leads you to in-depth understanding of the front-end animation, I believe that after reading you must have no small harvest ~ ⚾ if you are interested in this article welcome to praise attention + collection, more wonderful knowledge is waiting for you! 😘 πŸ€GitHub blogs at github.com/Awu1227. πŸ‰ I have other columns, please read ~ 🏐 play the beauty of CSS 🎱Vue from giving up to getting started 🎳 simple JavaScript