Front-end animation implementation notes
Notes written by me when I participated in ByteDance's youth training camp. This part is taught by Mr. Jiang Xiang.
Animation: Animation is the process of creating the illusion of motion and change by arranging in rapid succession successive images that differ only slightly from each other.
- fast
- Continuous arrangement
- very little difference
- create illusion
Animation needs to define two basic states, namely the start state and the end state, and then fill the gap between the two to make the animation coherent.
There are two ways to complete blanks:
- Motion tween: traditional animation. The lead artist draws the keyframes, and the tween animator adds them. (In the front end, the tween animator is done by the browser, such as keyframe and transition)
- Frame-by-frame animation: Each frame is drawn by the master artist. (e.g. sprite animation implemented by steps)
Common front-end animation technologies: Sprite animation, CSS animation, JS animation, SVG animation, WebGL animation
1. CSS Animations
CSS animation is a common implementation of CSS animation
- animation-name: A list of animations to apply. Each name represents an animation sequence defined by @keyframes
- animation-duration: the duration of an animation cycle (the default is 0s, which means no animation)
- animation-timing-function: The rhythm at which CSS animations are executed in each animation cycle
- animation-delay: animation delay playback
- animation-iteration-count: The number of times the animation will run before ending, either 1 time or an infinite loop
- animation-direction: Whether the animation is played in reverse
- animation-play-state: defines whether an animation is running or paused
1.1 translate (move)
Defines the translation transform of the element.
copydiv { width: 200px; height: 200px; background-color: red; animation: Translate infinite 4s linear; } @keyframes Translate { 0% { transform: translate(0, 0); } 25% { transform: translate(0, 200px); } 50% { transform: translate(200px, 200px); } 75% { transform: translate(200px, 0); } 100% { transform: translate(0, 0); } }
1.2 scale (zoom)
Zoom in and out of defined elements
copydiv { width: 200px; height: 200px; background-color: red; animation: Scale infinite 2s linear; transform-origin: 0 0; /*Zoom reference point*/ } @keyframes Scale { from { transform: scale(1, 1); } to { transform: scale(0.5, 0.5); /*The first and second parameters are the multiples of x-axis and y-axis scaling respectively*/ } }
1.3 rotate (rotate)
define the rotation of the element
copydiv { width: 200px; height: 200px; margin: 200px; background-color: red; animation: Scale infinite 4s linear; } @keyframes Scale { from { transform: rotate(0); } 100% { transform: rotate(360deg); } }
1.4 skew (tilt)
define the slope of the element
copydiv { width: 200px; height: 200px; margin: 200px; background-color: red; animation: Translate 1s linear forwards; } @keyframes Translate { from { transform: skew(0, 0); } to { transform: skew( 0, 45deg ); /* The first parameter is the tilt angle in the horizontal direction, and the second parameter is the tilt angle in the vertical direction */ /* transform: skew(45deg, 0); */ } }
1.5 CSS sprite animation
CSS steps to achieve frame-by-frame animation
Effect (you may not be able to see it if you open it directly, you may need to surf the Internet scientifically, this picture of Mr. Jiang Xiang seems to be put on github)
1.6 Advantages and disadvantages of CSS animation
Advantages: simple and efficient. Does not depend on the main thread, using hardware acceleration (GPU).
Disadvantages: The content of animation cannot be dynamically modified or defined, different animations cannot be synchronized, and multiple animations cannot be stacked
Usage scenario: simple H5 activity/promotion page
Related libraries: animation.css, shake.css
1.7 CSS properties
I don’t know why this part is placed in the SVG part, but I personally put it on the CSS side. (I feel like it might come in handy in the future)
2. SVG animation
SVG is an XML-based vector graphics description language that can work well with CSS and JS.
There are three ways to implement SVG animation:
- SMIL
- JS
- CSS
2.1 line
The principle of JS strokes: stroke-dashoffset and stroke-dasharray are used together to achieve stroke effects.
- The attribute stroke-dasharray controls the pattern of dashed lines used for strokes. It is an array specifying the length of dashes and spaces. If an odd number of values is provided, the array of values is repeated once. For example, 1,2,3 is equivalent to 1,2,3,1,2,3
- Attributes The stroke-dashoffset attribute specifies the distance of the dash pattern from the start of the path
copy<line stroke-dasharray="10, 5" x1="10" y1="10" x2="100" y2="10" /> <!-- 10 5 pixels for dashes, 5 pixels for white space. starting point is(10, 10), end point is(100, 10) -->
2.2 path
This part will be filled later
2.3 Demonstration
Not written by me. belongs to share link
2.4 SVG advantages and disadvantages
- Advantages: Realize animation through vector elements, and have better clarity under different screens. Can achieve special effects such as character tracing and deformation
- Disadvantages: Complicated to use (I am at a loss at this stage)
3. JS animation
JS can implement many complex animations, and can also manipulate canvas for drawing.
JS animation function encapsulation (used by Mr. Jiang Xiang in his lectures):
copyfunction animate({ easing, draw, duration }) { let start = performance.now(); // The reason for not using Date.now() is that performance.now() increments at a constant speed, accurate to the microsecond level, and is not easy to be tampered with 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 let progress = easing(timeFraction); draw(progress); // draw it if (timeFraction < 1) { requestAnimationFrame(animate); /* * Reasons to use RequestAnimationFrame instead of setTimeout or setInterval: * This method allows the callback function to run when the browser is ready to repaint, and quickly * When the page is in the background, there will be no redrawing, so the callback function will not run, so the animation will pause and will not consume resources */ } else { resolve(); } }); }); }
parameter:
easing: easing function. Determines how the execution progress changes over time, either linearly or non-linearly
copyeasing(timeFraction) { return timeFraction * 100; },
draw: draw function. Equivalent to a brush, it will be called repeatedly. The input parameter is the progress of the current execution, which is a number between 0 and 1
copyconst draw = (progress) => { ball.style.transform = `translate(${progress}px, 0)`; };
duration: duration
3.1 Uniform motion
copyconst draw = (progress) => { ball.style.transform = `translate(${progress * 100}px, 0)`; // 100 pixels per second }; animate({ easing(timeFraction) { return timeFraction; }, draw, duration: 1000, });
This part is still not very clear, and it is hooked up with mathematics (tired).
4. Optimization
Performance perspective: The general process of page rendering: JS -> CSS -> Calculation Style -> Layout -> Drawing -> Rendering layer merging. Among them, layout (rearrangement) and drawing (redrawing) are the two most time-consuming parts, so these two parts should be reduced as much as possible.