This is the 27th day of my participation in the August More Text Challenge

Js animation function encapsulation

Function selection

JavaScript animations should go through 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 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.

RequestAnimationFrame is a browser interface for timed loops that redraw a web page frame by frame, similar to setTimeout, but without the need for an interval.

  • RequestAnimationFrame takes as an argument a callback function that is invoked before the browser redraws.
  • The callback function is passed inDOMHighResTimeStampParameter, which is the same asperformance.now()The return value of therequestAnimationFrame()The time to start executing the callback function.
  • By default, requestAnimationFrame executes at a frequency of 1000/60, or 60 times per second (approximately once every 16.7 milliseconds).

function

Parameter Description:

  • Timing – Calculates 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. (When the animation is intended to be executed)
  • Draw – The function that draws an animation (that is, the way to draw an animation, it can be CSS, JS, SVG).
function animate ({timing, draw, duration}) {
    
    // Unlike other time functions (such as date.now ()), performance.now() increments at a constant rate and is subtle enough to be difficult to tamper with.
    let start = performance.now();   
    
    return new Promise(resolve= > {
        requestAnimationFrame(function animate(time) {
            TimeFraction goes from 0 to 1.
            let timeFraction = (time - start) / duration;
            if (timeFraction > 1) timeFraction = 1;

            Calculate the current animation state (calculate the current animation state)
            let progress = timing(timeFraction)
            
            draw(progress); // Draw it
            
            if (timeFraction < 1) {
               requestAnimationFrame(animate);
            } else{ resolve(timing); }}); }); }Copy the code

The formula

T time, r distance, v velocity

When time is constant, a special variable parameter is added to time, which changes with time, and the time becomes a variable time (time distortion). By changing time, the state of the curve is changed, and then a normal linear motion is changed

The following example can be seen here 👉 code address


Let’s use the functions we encapsulated above

Uniform motion

Motion with constant velocity

In the figure below, the horizontal axis is time T and the vertical axis is distance R

  • We define a function to draw an animationdrawTo implement an animation by modifying the TRANSFORM of the CSS
  • Time computes the animation progress, passing in a timeFraction period

The force of gravity

  • The effect is to fall from the top, by changing the value of translateY
  • TimeFraction **2 is t to the second power

Friction (uniform deceleration)

If an object moves in a straight line and its speed decreases uniformly with time, the motion is called uniformly decelerated linear motion

Horizontal cast

  • The draw function controls two attributes X and Y of Translate
  • X-axis constant velocity, Y-axis acceleration

Related work practice

The development of resources

Animation code examples

codepen.io/

codesandbox.io/

Design website

dribbble.com/

Animation is generally used in UE and UI

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

Animation Library resources

SVG

  • Snap.svg – 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.
  • Velocit.js.- 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 – JavaScript canvas library that supports animation.
  • Paper.js – Swiss Army Knife of Vector Graphic Scripts – Scriptographer using HTML5, Canvas ported to JavaScript and browsers.
  • Pixijs – Create beautiful digital content using the fastest and most flexible 2DWebGL renderer.

Work practice

When receiving a new animation requirement, the process looks something like 👉 [Animation Frames -> Code & Design File > Code Conversion]

There are a couple of things that could happen

  • You need to develop your own 👉 completely (you can use the packaged animation library, which is a trade-off between development cost and experience).
  • Design is not very free 👉 (sharpness, picture format can be specified, animation as far as possible to give a hint or similar case reference. Request Sprite resources, resources, etc. Need help compression.
  • Design resources are sufficient 👉 (design export in Lottie format is required).

Lottie

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.

【 Advantages of Lottie 】

The Lottie method scheme is generated by the designer, exported to JSON, and played to the front end. So, the benefits of using Lottie schemes are

  • Animation by the design of the use of professional animation production tools Adobe After Effects to achieve animation more convenient, animation effect is better;
  • The front end can easily call the animation, and control the animation, reduce the front-end animation workload;
  • Animation design and production, front-end display animation, professional people do professional work, reasonable division of labor;
  • Seller show is buyer show, restore degree 100 percent;
  • Using the Lottie scheme, json files are much smaller than GIF files and have better performance.

【 Lottie deficiency 】

  • The Lottie-Web file itself is still large, lottie.js is 513K, the lightweight version is 144K compressed, and gzip is 39K. So, be aware of lottie-Web loading. At present, H5 project has offline packages, and PC project also has PWA, which will be cached to ensure the loading speed.

  • Lottie animation can actually be understood as SVG animation/Canvas animation. It cannot add animation effects to existing HTML.

  • The export of animation JSON file is currently to export the parameters in AE into JSON content. If the designer builds a lot of layers, the json file may still be too large (20KB). There are certain norms that designers need to follow.

  • There are a very small number of AE animations that Lottie cannot implement, some due to performance issues and some that are not done. For example: Stroke animation, etc.

Optimization of animation

  • User Experience perspective

    The Guide To CSS Animation: Principles and Examples

  • 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. In terms of performance, an ideal rendering pipeline is one that has no layout and no drawing, just the merging of rendering layers.

How do I know which CSS property changes affect these two links?

Here’s how each CSS property affects it. Check it out at 👉csstriggers.com

In the actual application, some simple optimization methods

  • Do not use the display: None attribute to trigger the start of the animation. (Since it causes Layout and Paint, switching the class name is already a good idea.)

  • Translate values replace top/left/right/bottom switches, scale values replace width/height, opacity values replace display/vibility, 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 the net can be greatly improved.

The following properties 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.

Other optimization methods

  • Algorithm to optimize
    • Linear functions instead of real calculations
    • Geometric model optimization
    • Collision detection optimization
  • Memory/cache optimization
  • Off-screen drawing

conclusion

I attended the byte youth training camp, so I prepared a re-learning front-end series. Due to the time, I may only be able to learn notes.

The lecturer of this class: Byte e-commerce front-end — Jiang Xiang

If any of the above is wrong, please point out in the comments section!


If there is a harvest, leave a thumbs-up to encourage it! 🍜