background
- Front-end animation scene demand
- The choice of technical implementation scheme for many animation scenes is vague
- The merits and demerits of each animation scheme and the understanding of applicable scenes are vague
- Existing animation library too many, do not know which to choose
- Mainstream animation library has a vague understanding of applicable scenes
First of all, let’s classify the entire animation system from various angles, so that we can clearly understand the entire animation system.
classification
1.1 Usage Angle
First of all, we divide animation into display animation and interactive animation from the perspective of its use or business.
1.1.1 Display animation
It’s like a GIF, or a video. For example, when opening the chest, we added a cut-scene transition animation instead of waiting for the result. There are many ways to realize display animation in the actual scene, such as using GIF, Canvas, CSS3 animation, etc., but the final output is not interactive, that is, from the initial state of animation to the end state in one go. Users can perceive this process, but cannot participate in it.
1.1.2 Interactive animation
For interactive animation, we can trigger the corresponding operation at a certain time when the animation plays, so that users can participate in the animation. The most common example is red envelope rain, which can not only improve user experience, but also enhance the diversity of our products. However, one of the problems that interactive animation often faces is that it is very complex to implement interactive animation through native code, and performance and compatibility are issues that have to be seriously considered. A better solution is to look for related frameworks.
1.2 Drawing technical Angle
No matter how you animate it, you end up on the front page in one of three ways:
- Canvas
- div
- SVG
PS: Video can also be used for simplicity, but unless the playing scene of animation is fixed, the playing display of mobile video is not quite the same in different apps, different models and different systems, which is easy to step on a lot of holes.
1.2.1 Performance differences of different rendering technologies
- canvas
- High efficiency, good performance, high controllability, can only handle bitmaps, constant memory footprint
- Resolution dependent
- Event handlers are not supported
- Weak text rendering capability
- Ability to save the resulting image in.png or.jpg format
- Best suited for graphics-intensive games, where many objects are frequently redrawn
- SVG
- Vector processing, no distortion
- Resolution independent
- Support event handlers
- Best for applications with large rendered areas (such as Google Maps)
- High complexity slows down rendering (any application that overuses DOM is not fast)
- Not suitable for game applications
- div
- Including CSS control of DOM animation, JS control of DOM animation
- More suitable for a simple number of less complex animation
1.2.2 Comparison between Canvas and SVG
In a word: all 2D graphics, SVG is vector graphics, canvas is bitmap. Canvas is rendered pixel by pixel and is suitable for games.
SVG
- SVG draws vector images and scaling does not affect the display, so it is best suited for applications with large rendered areas (such as Google Maps)
- SVG is a language for describing 2D graphics using XML.
- SVG is based on XML, which means that every element in the SVG DOM is available. You can attach JavaScript event handlers to an element.
- In SVG, every graph that is drawn is treated as an object. If the attributes of an SVG object change, the browser can reproduce the graphics automatically.
Canvas
- Canvas uses JavaScript to draw 2D graphics.
- Canvas is rendered pixel by pixel.
- In canvas, once the graph has been drawn, it doesn’t continue to get attention from the browser. If its position changes, the entire scene also needs to be redrawn, including any objects that may have been covered by the graph.
- Canvas occupies only one DOM node, and it has better performance than CSS/SVG when it does animations with a lot of moving elements such as fireworks and snow
Performance comparison
- In general, as the screen size increases, the canvas will start to degrade because more pixels need to be drawn.
- As the number of objects on the screen increases, SVG will start to degrade as we continue to add these objects to the DOM.
- These metrics are not necessarily accurate, and differences in implementation and platform, whether fully hardware-accelerated graphics are used, and the speed of the JavaScript engine are bound to cause variation
1.3 Animation type Angle
Front-end dynamic effect development, the first thing to determine is the purpose of animation -> confirm the type of animation -> confirm the drawing technology -> confirm the realization of animation. Although the final presentation of animation carrier (drawing technology) is three, but there are many ways to achieve animation, we have to start from the type of animation to discuss the implementation of animation:
- Frame by frame animation (sequence frame animation)
- GIF implementation
- CSS implementation (Animation)
- JS + DOM implementation
- JS + canvas
- Tween animation/Keyframe animation
- CSS implementations (transition, animation, etc.) use some easing functions
- JS implementation
- SVG animation
- Define graphics using XML format
- SVG images can be generated using AI and other SVG editing tools, and then animated with existing libraries such as Animos. js and GSAP
- Skeletal animation
- Use tools such as Spine and DragonBones to export resource images and JSON animations to configure resources.
- 3 d animation
- DOM manipulation is implemented with CSS 3D. (
perspective
Attributes,css3d-engine) - WebGL (three.js, etc.) for scene building
- Export 3D model animations in Blender or Maya
- DOM manipulation is implemented with CSS 3D. (
1.3.1 Frame by frame Animation (Sequence Frame Animation)
Frame by frame animation is to draw frame content frame by frame in time frame, because it is a frame by frame painting, so frame by frame animation has very great flexibility, almost can show any content you want to show.
Due to the different contents of the frame sequence of the animation frame by frame, not only increase the production burden and the final output of the file is also very large, but its advantages are also obvious: because it is similar to the movie playback mode, it is very suitable for the performance of very delicate animation, such as 3D effect, characters or animals turn around sharply and so on.
So what is the core of frame-by-frame animation? It is to play these static pictures in a fast loop to form a dynamic animation effect. This is frame animation
1.3.1.1 GIF implementation
We can export frame animation to GIF, GIF will play continuously, can not be paused, it is often used to achieve small detail animation, low cost, easy to use. But the disadvantages are also obvious:
- Image quality, GIF support less color (maximum 256 colors), poor Alpha transparency support, image jagged edge more serious;
- Interactive, can not directly control play, pause, play times, poor flexibility;
- Performance, GIF will cause the page periodic painting, poor performance.
1.3.1.2 CSS implementation
CSS3 frame Animation is the program we need to focus on today. The core is to use Animation Animation in CSS3. Specifically, steps(number_of_steps, direction) of animation-timing-function is used to implement the sequential playback of the animation frame by frame.
The realization principle of frame animation is to constantly switch the content of visual images, and use the physiological phenomenon of visual retention to realize the animation effect of continuous playback. Here we introduce several schemes of making CSS3 frame animation.
(1) Continuously switch the animation image address SRC (not recommended) We put the image in the background of the element (background-image), and change the value of background-image to achieve the frame switch. However, this method will have the following disadvantages, so this scheme is not recommended.
- Multiple images can result in multiple HTTP requests
- The first time each image is loaded will cause a flicker when switching images
- It is not conducive to file management
(2) Continuously switch the position of Sprite image (recommended) We combine all animation frames into one Sprite image, and realize the animation frame switch by changing the value of background-position. Proceed in two steps:
Step 1: Combine the animation frames into Sprite images. The requirements of Sprite images can be prepared by looking at the above materials, such as the following Sprite image, a total of 20 frames.
Step 2: Use the Steps step function to switch the position of Sprite image.
<div class="sprite"></div>
.sprite {
width: 300px;
height: 300px;
background-repeat: no-repeat;
background-image: url(frame.png);
animation: frame 333ms steps(1,end) both infinite;
}
@keyframes frame {
0% {background-position: 0 0; }5% {background-position: -300px 0; }10% {background-position: -600px 0; }15% {background-position: -900px 0; }20% {background-position: -1200px 0; }25% {background-position: -1500px 0; }30% {background-position: -1800px 0; }35% {background-position: -2100px 0; }40% {background-position: -2400px 0; }45% {background-position: -2700px 0; }50% {background-position: -3000px 0; }55% {background-position: -3300px 0; }60% {background-position: -3600px 0; }65% {background-position: -3900px 0; }70% {background-position: -4200px 0; }75% {background-position: -4500px 0; }80% {background-position: -4800px 0; }85% {background-position: -5100px 0; }90% {background-position: -5400px 0; }95% {background-position: -5700px 0; }100% {background-position: -6000px 0;}
}
Copy the code
Questions about the above animation?
Q1: Since we have defined keyframes in detail, can we not use steps function and directly define linear variation?
animation: frame 10s linear both infinite;
Copy the code
If we define it this way, the animation will not be performed step by step, but will continuously change the position of the background image. It is a moving effect, not a switching effect, as shown below:
Question 2: Shouldn’t it be set to 20 steps, how did it become 1? The animation-timing-function property is used to describe the animation-timing-function property. The CSS animation-timing-function property defines the pace at which the CSS animation executes during each animation cycle.
To sum up, we can see that since we have defined an animation cycle in detail, that is, one change between 0% and 5%, and one change between 5% and 10%, we can achieve the desired effect by writing this way.
Method 2:
<div class="sprite"></div>
.sprite {
width: 300px;
height: 300px;
background-repeat: no-repeat;
background-image: url(frame.png);
animation: frame 333ms steps(20) both infinite;
}
@keyframes frame {
0% {background-position: 0 0; }/ / can be omitted
100% {background-position: -6000px 0;}
}
Copy the code
Here, we defined the start and end of the key frame, that is, a key frame period, but since we did not define the display of each frame in detail, we need to divide the interval from 0% to 100% into 20 steps for staged display.
(3) Moving the position of Sprite image continuously (recommended on mobile terminal) is basically the same as the second one, except that the process of switching the position of Sprite image is changed to transform: translate3D (), but there is an extra layer of overflow: hidden; Here, we take defining only the initial and end frames as an example. Using Transform can enable GPU acceleration, improve machine rendering effect, and effectively solve the problem of animation jitter of mobile terminal frames.
<div class="sprite-wp">
<div class="sprite"></div>
</div>
.sprite-wp {
width: 300px;
height: 300px;
overflow: hidden;
}
.sprite {
width: 6000px;
height: 300px;
will-change: transform;
background: url(frame.png) no-repeat center;
animation: frame 333ms steps(20) both infinite;
}
@keyframes frame {
0% {transform: translate3d(0.0.0); }100% {transform: translate3d(-6000px,0.0);}
}
Copy the code
The steps(number_of_steps, direction) function of animation-timing-function is used to implement the sequence of animation frames.
Next let’s look at the steps() function:
Steps specifies a step function that takes two parameters:
- The first argument specifies the number of intervals in the function (it must be a positive integer);
- The second optional parameter specifies the step change at the start or end of each interval. It accepts both start and end values. The default is end.
- Start frame 1 is the end of the first animation, end frame 1 is the start of the first animation
In addition to the steps function, animation-timing-function also has two frame-by-frame animation properties: step-start and step-end:
- Step-start equals steps(1,start)
- Step-end equals steps(1,end)
1.3.1.3 JS implementation
(1) Using JS to control the switch of SRC attribute of IMG (not recommended) is the same as switching background-image attribute of CSS3 frame animation above, there will be multiple requests and other problems, so we do not recommend this scheme, but it is a solution.
(2) Control the drawing of Canvas image through JS. The principle of making frame animation through Canvas is to draw the picture on Canvas with drawImage method, and the desired effect can be obtained by constantly erasing and redrawing.
<canvas id="canvas" width="300" height="300"></canvas>
(function () {
var timer = null,
canvas = document.getElementById("canvas"),
context = canvas.getContext('2d'),
img = new Image(),
width = 300,
height = 300,
k = 20,
i = 0;
img.src = "frame.png";
function drawImg() {
context.clearRect(0.0, width, height);
i++;
if (i == k) {
i = 0;
}
context.drawImage(img, i * width, 0, width, height, 0.0, width, height);
window.requestAnimationFrame(drawImg);
}
img.onload = function () {
window.requestAnimationFrame(drawImg);
}
})();
Copy the code
The above animation effect is achieved by changing the x-coordinate position of the cropped image, or by changing the coordinate position of the image placed on the canvas, as follows: context.drawImage(img, 0, 0, width*k, height,-i*width,0,width*k,height); .
(3) Control CSS property value changes through JS
This method is the same as the previous CSS3 frame animation, there are three ways, one is to switch the element background image address background-image by JS, the other is to switch the element background image location background-position by JS, Transformate3d () : translate3D () : translate3D () : translate3D () : translate3D () : translate3D ()
- Toggles element background image position
background-position
.sprite {
width: 300px;
height: 300px;
background: url(frame.png) no-repeat 0 0;
}
<div class="sprite" id="sprite"></div>
(function(){
var sprite = document.getElementById("sprite"),
picWidth = 300,
k = 20,
i = 0,
timer = null;
// Reset the background image position
sprite.style = "background-position: 0 0";
// Change the background image position
function changePosition(){
sprite.style = "background-position: "+(-picWidth*i)+"px 0";
i++;
if(i == k){
i = 0;
}
window.requestAnimationFrame(changePosition);
}
window.requestAnimationFrame(changePosition); }) ();Copy the code
- Moves element background image position
transform:translate3d()
.sprite-wp {
width: 300px;
height: 300px;
overflow: hidden;
}
.sprite {
width: 6000px;
height: 300px;
will-change: transform;
background: url(frame.png) no-repeat center;
}
<div class="sprite-wp">
<div class="sprite" id="sprite"></div>
</div>
(function () {
var sprite = document.getElementById("sprite"),
picWidth = 300,
k = 20,
i = 0,
timer = null;
// Reset the background image position
sprite.style = "The transform: translate3d (0, 0)";
// Change the background image movement
function changePosition() {
sprite.style = "transform: translate3d(" + (-picWidth * i) + "Px, 0, 0)";
i++;
if (i == k) {
i = 0;
}
window.requestAnimationFrame(changePosition);
}
window.requestAnimationFrame(changePosition); }) ();Copy the code
1.3.1.4 Performance analysis
We checked the FPS, CPU usage, GPU usage, Scripting, Rendering, Painting and memory usage of each scheme through various Chrome tools, and obtained the following data:
Performance – Scheme | cssbackground-position |
csstransform:translate3d() |
JS Canvas | JSbackground-position |
JStransform:translate3d() |
---|---|---|---|---|---|
FPS | 60 | 51 | 60 | 60 | 60 |
CPU | 5% – 6.2%. | 0.3% – 1%. | 7% – 8%. | 6% – 8%. | 6% – 8%. |
GPU | 3.8 MB | 4-10MB | 0 | 3.8 MB | 4-11MB |
Scripting | 0 | 0 | 2.51% | 2.61% | 3.18% |
Rendering | 1.17% | 0.141% | 0.84% | 1.65% | 2.71% |
Painting | 1.58% | 0.01% | 1.63% | 1.75% | 1.05% |
memory | 20112K | 21120K | 21588K | 20756K | 21576K |
Through the analysis of the above data, we can draw the following points:
- In addition to the CSS
transform:translate3d()
The other options have a smooth FPS of 60FPS, but the FPS of this option is not too low. - The CSS has the lowest CPU usage
transform:translate3d()
Solution. - The scheme with the lowest GPU occupancy is THE JS Canvas drawing scheme.
- CSS schemes have no scripting overhead
- The least Rendering is CSS
transform:translate3d()
Solution. - The least Painting is CSS
transform:translate3d()
Solution. - There is little difference in memory usage among schemes.
Conclusion: We saw that CSS Transform: Translate3D () achieved the lowest performance in 4 of the 7 metrics, which makes it a reasonable choice for CSS frame animation.
1.3.2 Tween Animation/Keyframe Animation
Tween animation is one of the basic forms of animation, which is also called intermediate frame animation and gradient animation. It refers to an animation form in which the key state of the animation is artificially set, namely the key frame, and the transition process between the key frames only needs to be processed and rendered by the computer. To put it bluntly, when we do animation, we only need to specify the states of animation at several special moments, and the rest states are automatically calculated by the computer.
The common means to realize tween animation are mainly as follows:
- CSS3 Animation: Inserts a tween Animation between each keyframe using the Animation (a time function other than steps()) property.
- CSS3 Transition: Different from animation, Transition can only be configured
The initial
andThe end of the
Two keyframe states at the moment. - Implement animations in JavaScript: such as the JavaScript animation library or framework, animos.js or TweenJS, which is one of the CreateJS suites. In addition, the GreenSock Animation Platform (GSAP), which has long been famous in the Flash industry, also introduced the support for Javascript Animation.
1.3.2.1 CSS implementation
Transition allows CSS properties to transition smoothly within a certain period of time, that is, to specify the initial state and the end state of an element. You can complete an animation, and the changes in the middle are entirely up to the browser’s own decision. We’re going to look at the transition properties. However, animations made using Transition have significant disadvantages:
- Transition needs to be triggered by an event, so it can’t happen automatically when a web page loads.
- Transition is a one-time thing. It cannot happen again and again unless it is triggered again and again.
- Transition can only define a beginning state and an end state, not an intermediate state, so there are only two states.
- A transition rule defines only one property change, not multiple properties.
Animation can be used to complete a complete CSS tween animation. As mentioned above, we only need to define the animation state at several special moments. This particular moment is usually called a keyframe.
Keyframes has its own syntax. It is named with “@keyframes”, followed by the “name of the animation” and curly braces “{}”, which are the style rules for different periods of time, just like CSS style rules.
For a style rule in “@keyframes” that is composed of multiple percentages, such as between “0%” and “100%”, we can create multiple percentages in this rule, and we can add different attributes to each percentage for the elements that need to be animated, so that the elements can achieve a constantly changing effect. Such as moving, changing element color, position, size, shape, etc.
One thing to note, though, is that we can use “fromt” and “to” to represent where an animation starts and ends, which means that “from” equals “0%” and “to” equals “100%”. It’s worth noting that “0%” can’t be omitted like other properties. We must add the percentage sign (” % “) here. If not, our keyframes are invalid and do nothing. Because units of keyframes only accept percentage values. Take a look at the code:
@keyframes IDENT {
from {
Properties:Properties value;
}
Percentage {
Properties:Properties value;
}
to {
Properties:Properties value; }}/* or write it all as a percentage: */
@keyframes IDENT {
0% {
Properties:Properties value;
}
Percentage {
Properties:Properties value;
}
100% {
Properties:Properties value; }}Copy the code
IDENT is the name of the animation, you can do whatever you want, it’s better to be a little bit more semantic, Percentage is the Percentage value, we can add a lot of percentages, Properties is the name of the CSS property, left,background, etc., Value is the attribute value of the corresponding attribute.
1.3.2.2 JS implementation
Animations can be implemented in JavaScript using an open source JavaScript animation library or framework, such as animos. js or TweenJS. Here we use animos. js as an example to demonstrate how to implement a tween animation.
- To some extent,
anime.js
Is also aCSS 3 animation library
Apply to allCSS properties
, and realized@keyframes
Can realize frame animation more conveniently, replace CSS3 complex definition way.Define each frame as an array of objects
Poke me: Keyframes instance
anime({
targets: 'div'.translateX: [{value: 250.duration: 1000.delay: 500.elasticity: 0 }, / / the first frame
{ value: 0.duration: 1000.delay: 500.elasticity: 0 } / / the second frame]})// This example implements the horizontal displacement of the target element in two frames
Copy the code
- To provide the
Timeline
I can do more complex animations with thisTimeline
, we can maintain the relationship between different animations, and then form a more complex animation through multiple different animations.
Poke me: Timeline instance
var myTimeline = anime.timeline();
// Add the animation with the.add() method
myTimeline
.add({
targets: '.square'.translateX: 250
})
.add({
targets: '.circle'.translateX: 250
})
.add({
targets: '.triangle'.translateX: 250
});
Copy the code
1.3.3 SVG animation
When we are in the realization of animation, slowly will find that most of the elements are images, and image is programmed in advance, can’t change, can replace with new image, when we smile to achieve animation, for example, need to draw two pictures, one is with their mouth closed, one was grinned, then play by frame. When you have enough frames, it doesn’t look stiff. Once you get below 24 frames, it becomes unnatural. How can you achieve smooth changes without increasing the workload? We grafted the thinking of keyframe animation to the distortion of the element itself, thus giving birth to the concept of “flexible animation”.
1.3.3.1 SVG animation explanation
As can be seen from the above figure, elements can change with each other and are very smooth. Such animation does not need Canvas as a heavy weapon, but can be realized with simple DOM. SVG is really a magic tool, which not only has distinctive features in realizing ICONS and fonts, but also has its own school in realizing flexible animation.
SVG is still DOM, it has its own Animation tag, but it also supports CSS properties, which implement AnimationThe essence is dependent on line and filling. The change of line leads to the change of filling area, thus causing the change of shape. And the line is dependent on the path and anchor point, path and anchor point change, directly affect the change of the line.
SVG images can be generated using AI and other SVG editing tools, and then animated with existing libraries such as Animos. js and GSAP
Here we implement an SVG path animation using animo.js to draw the path to poke me: SVG instance
var path = anime.path('.motion-path-demo path');
anime({
targets: '.motion-path-demo .el'.translateX: path('x'),
translateY: path('y'),
rotate: path('angle'),
easing: 'linear'.duration: 2000.loop: true
});
Copy the code
1.3.4 Bone animation
SVG’s animations are small and local, with a narrow range of applications, but when it comes to complex, flexible animations, and even games, bone animations are still needed.
From the picture above, we can see that the dragon’s wings are a picture, but the muscle contraction and relaxation brought by the flapping of the wings can be realized through local distortion and deformation of the picture. How does this animation work? This brings us to a very important concept in bone animation:The grid.
Here we discuss this concept in a superficial way. In order to achieve local changes in an image, we need to divide the image into blocks, and each block is called a grid. Each grid has its own vertices and edges. Whether the concept of grid is very similar to path and anchor point, no matter what technology, the implementation logic is similar. The important thing is not to always focus on the different and changing parts, but to find those unchanged places, so as to achieve the effect of connecting by analogy.
Making animations like this isn’t complicated — you can use tools like Spine and DragonBones — but it’s really a manual job, and you need to constantly tweak it to get to a point where it looks comfortable.
1.3.4.1 Skeleton animation explanation
Bone animation is to bind pictures of various body parts of a character to “bones” that interact with each other, and generate animation by controlling the position, rotation direction and zooming in and out of these bones.
Bone animation is usually divided into two parts:
- Skeleton
- Skin
Skeleton data includes two aspects:
- One is the topology of the skeleton (connection, parent-child relationship)
- The other is the various poses of the skeleton, that is, the position information of the whole skeleton corresponding to each action.
Skin can express is attached to the bone on the vertex information binding process is to determine each vertex is affected by which a few bones, the weights of every bone influence, such as the elbow skin may also affected by the arm and forearm two bones, away from the elbow part may be only affected by forearm bones. Generally in 3D skeleton animation, each vertex can support up to 4-8 bones at the same time and it can be very accurate to express the effect of the entire skin.
Advantages of bone animation: Bone animation requires higher processor performance than traditional frame-by-frame animation, but it also has more advantages:
1. Animation is more vivid 2. Image resources account for the smallest storage space: the image capacity of bone animation can be reduced by 90% (details of the compression scheme of configuration file H5 are described below) 3. 4. Skeleton is controllable: the skeleton can be controlled by code, the character equipment can be easily replaced, and even the skeleton can be controlled or monitored for special events. Skeleton event frame: animation executes to an action or a frame, triggering custom event behavior 6. Action data inheritance: multiple characters can share a set of animation data. 7. Combine physics engine and collision detection.Copy the code
1.3.4.2 Bone animation production
First let’s take a look at how bone animation is made:
The main tools used for bone animation are Spine and DragonBones
DragonBones
Dragonbones.com/cn/index.ht…
DragonBones started with Flash animations to reduce the amount of resources available while allowing for more fine-grained actions (such as interactive ones) to free up the art from the tedious task of drawing Sprie Sheets frame by frame. So it breaks each frame of a character’s Sprite sheet into smaller base blocks, such as arms, legs, torso, etc., and each base block is still the smallest controllable unit.
The following game & rendering engines all support rendering DragonBones exported files:
Spine
zh.esotericsoftware.com/
Spine is a 2D bone animation editing tool for games. Spine aims to provide a more efficient and concise workflow to create the animations required for games. The following game & rendering engines support the rendering of exported files from Spine:
Now let’s make a small case of bone animation
Create the skeleton
First we need to create the skeleton of the hand, as shown below:
Make sure the SETUP mode is in the upper left corner. 2. Make sure the root skeleton is selected in the right view. Click the Create button in the lower left corner. 4. Start creating the five skeletonsCopy the code
Create a skin grid
Then we need to create a skin MESH for the hand, as shown below:
First, click the Create button to exit the skeleton creation mode. 1. Select The Hand map (Attachment) 2. Select the Mesh option at the bottom of it 3. Click the Edit button in the lower right corner. 4. Click the Create button in the Edit Mesh menu 7. 8. Move the vertices by clicking the Modify button in the Edit Mesh menuCopy the code
Sets grid point weights
We need to set the weight of each skeleton to the mesh vertices, as shown below:
First, close the Edit Mesh menu. 1. Make sure that the hand texture is still selected. Click the Weights button in the lower left corner and call out the Weights menu 3. Click the Bind button at the bottom of the Weights menu to Bind the bones. 4. Select the five bones of the hand until they all appear in the Weights menu. Click the Auto button on Weights menu or press 'ESC' to trigger Spine's automatic weight calculation 6. Check the Weights menu Overlay and we can see the weight map after bindingCopy the code
Move! Now we’re going to get the manual up, and we’re just going to show an animation of a bent arm. First, we need to set the keyframe, let’s set the keyframe on frame 1 and frame 30, the arm position of these two keyframes is exactly the same, because we need to loop the animation.
The specific steps are shown below:
1. Ensure that the mode in the upper left corner is in ANIMATE mode. 2. Select frame 0 4. Click the key button under Rotate and set keyframe 5 for the rotation property of the arm. Select frame 30 6. Repeat step 4 so that the key frame of frame 30 is exactly the same as that of frame 0Copy the code
Then we simply rotate the arm and find a frame between 0 and 30 as the keyframe: we select frame 15 as the intermediate keyframe.
1. Select frame 15 2. Make sure the Rotate button is selected 3. Press K frame button to set key frame 5. Press Play button to preview animationCopy the code
As an added bonus, I made MESH for the other hand, mouth, face and hair. Here is how the animation looks:
1.3.4.3 Display bone animation at the front end
Spine was used to export the bone animation and output resources (combined image information file: Atlas; Animation information file: JSON, picture combination: PNG), these resources are handed over to the front end for display.
Front-end development basisSpineorDragonBonesIt can support the rendering engine and import the rendering engine into the project to display the bone animation. The following figure is the bone animation exported by Spine through PixiJS.
1.3.5 3 d animation
The front-end 3D animation implementation can be implemented using CSS 3D through perspective property operations, or directly with the help of the open source library Three.js. Since 3D animation involves a lot of content and space is limited, we will dedicate a chapter on front-end 3D animation. (The water is deep here, young man. You can’t hold it.)
Summary of existing schemes
2.1 Pure CSS implementation
Suitable scene: simple show animation
Use the transition\animation property to set the corresponding keyframe state, and use some easing functions to implement some simple animations.
Advantages:
- The development cost is low and there is no need to import any additional dependency packages
Disadvantages and shortcomings:
- Can only be competent to do some relatively simple animation, unable to achieve some too responsible animation.
2.2 Anime. Js
Applicable scene: simple display animation + weak interactive animation
Animo.js is a lightweight JS-driven animation library with the following features:
1. Support keyframes to connect multiple animations 2. Support Timeline, which makes it possible to achieve more complex animations 3. Supports animation state controls for Playback control, playback, pause, restart, and search for animations or timelines. 4. Support animation state callback, which provides a callback function at the beginning, execution, and end of animation 5. Support SVG animation 6. Custom Bezier curves 7. Any DOM attribute containing a numeric value can be set to animationCopy the code
GitHub:github.com/juliangarn…. Codepen repository: codepen. IO /collection…. Document demonstration: animejs.com/documentat….
Function introduction:
- To some extent,
anime.js
Is also aCSS 3 animation library
Apply to allCSS properties
, and realized@keyframes
Can realize frame animation more conveniently, replace CSS3 complex definition way.Define each frame as an array of objects
Poke me: Keyframes instance
anime({
targets: 'div'.translateX: [{value: 250.duration: 1000.delay: 500.elasticity: 0 }, / / the first frame
{ value: 0.duration: 1000.delay: 500.elasticity: 0 } / / the second frame]})// This example implements the horizontal displacement of the target element in two frames
Copy the code
- To provide the
Timeline
I can do more complex animations with thisTimeline
, we can maintain the relationship between different animations, and then form a more complex animation through multiple different animations.
Poke me: Timeline instance
var myTimeline = anime.timeline();
// Add the animation with the.add() method
myTimeline
.add({
targets: '.square'.translateX: 250
})
.add({
targets: '.circle'.translateX: 250
})
.add({
targets: '.triangle'.translateX: 250
});
Copy the code
- Common controls for animation playback are Pause, replay, continue, animation state tracking, auto play, loop count, and Jitter
- Provides callback functions for animations that are executed at the beginning, during, or during the completion of an animation or timeline. Poke me: Callback instance
var myAnimation = anime({
targets: '#begin .el'.translateX: 250.delay: 1000.begin: function(anim) { // callback
console.log(anim.began); // true after 1000ms }});Copy the code
-
Promises are supported, and when the animation is over, a call to animo.finished returns a Promise object. Poke me: Promise instance
-
SVG drawing path support, currently does not support Canvas drawing stamp me: SVG instance
-
For element tags with values such as input, you can also animate me with a Anime instance: the DOM ATTRIBUTES instance
anime({
targets: input,
value: 1000.// Animate the input value to 1000
round: 1 // Remove decimals by rounding the value
});
Copy the code
Advantages:
- Obviously,
anime.js
Not only did it happenCSS 3 animation
The depth of encapsulation, more through THE JS driver to achieve the state of operation animation,timeline
The realization of multiple branch animation management, for the realization of more complex animation provides the possibility - through
anime.js
To provide theplayback controls
andcallback
At the same time, forpromise
Support for animation, so that we have room for simple interaction animation - Although not supported
canvas
, but supportSVG drawing path
- Browser compatibility is good,
Android 4
All the above supported
Disadvantages:
anime.js
It is competent to do display animation, but it is also difficult to achieve especially complex animation. In terms of interactive animation, it still needs to see the scene. It is more suitable for doing some small interactive animation, such as playing football with touch screen and strong interaction.anime.js
Not so much.
2.3 Lottie
Applicable scene: complex display animation
The animation produced in AE is exported into a JSON file through the Bodymovin plug-in on AE, and the JSON is analyzed by Lottie. Finally, the animation is rendered in the way of SVG/ Canvas/HTML. It can perfectly display all kinds of complex animations designed by designers
IO/Lottie/Codepen Warehouse: Codepen.io /collection….
Advantages:
- Cross-platform, draw once, convert once, and use anywhere
- File smaller, get AE export
JSON
, finally passedlottie
Apply colours to a drawing forCanvas/SVG/HTML format
- Some properties of the animation, such as animation speed, can be manipulated through the API; Add callback functions for each state of the animation
- The animation is all in
After Effects
Is created in theBodymovin
Export, and native rendering requires no additional engineering work. - Liberate the productivity of front-end engineers and improve the freedom of designers to make dynamic effects
Disadvantages:
Bodymovin
There are still some AE effects that cannot be exported successfully- Support for interaction is not very good, more used to display animation
Lottie
对json
File support needs to be improved, some of them can be exported successfully at presentjson
Files don’t work well on mobile devices- Many AE effects are not Supported
2.4 PixiJs
Applicable scenarios: interactive animation, animation games
PixiJS is a 2D rendering engine. Pixi is responsible for rendering images. You can create rich interactive graphics, animations, and games without having to dig into the WebGL API or deal with browser and device compatibility issues. PixiJS, meanwhile, has full WebGL support and can seamlessly fall back to HTML5’s canvas if needed. PixiJs uses WebGL rendering by default. You can also specify canvas rendering by declaration. WebGL is not supported by Android 4.4 Browser on mobile, but canvas elegant degradation can be used.
Making: github.com/pixijs/pix…. The official document: pixijs. Download/releas… Official website: www.pixijs.com/ Examples: pixijs. IO/Examples /#/…
Features (from official DOCS) :
- support
WebGL rendering
- support
Canvas rendering
(PixiJS is now officially the fastest canvas rendering) - Very simple to use
API
- Rich interaction events, such as full mouse and mobile touch events
Pixi
The use andCanvas Drawing
Almost the same API, but different fromCanvas
The drawing API that uses Pixi to draw graphics is passedWebGL
inGPU
On the rendering- There are also a number of features that you need to know after learning PixiJs
Advantages:
- The greatest advantage is passing
WebGL
To call the GPU to render animation, which greatly improves performance - No need to know
WebGL API
Or is itBrowser compatibility
(For the following reason) - support
canvas
Rollback: The current device does not support rollbackWebGL
When,PixiJs
Will useCanvas rendering
animation - The complete
DOCS
A more active community is conducive to in-depth learning. However, I feel that the cost of learning PixiJs is relatively high
Disadvantages:
- The first is the compatibility issue, WebGL in
The Android 4.4
Is not supported and can only be degraded using canvas - Pixi is mainly for rendering, many other features developers have to write or use with other libraries, but so far, it works for our needs.
Performance:
- For the mobile version
Android4.4
The above phones, in addition to the code level caused by the performance is insufficient, through WebGL call GPU rendering, performance is guaranteed. However, Android4.4 can only use canvas rendering, performance still depends on the complexity of animation, and code optimization
2.5 summarize
Simple presentation animations: For simple animations, we can first try using the transition\animation property of native CSS.
Simple display-based animation + weak interaction: Simple interactive behaviors are required for simple animation display, for example, the user clicks to pause the corresponding operation, and the animation continues to play when the operation is completed. In terms of weak interaction, animos.js scheme can be adopted.
Animo.js not only supports all CSS properties, but also controls animation execution through Timeline, callback, and Playback controls, and animo.js works with SVG animation.
Complex display animation:
- If the resources required are small, consider using GIF or frame-by-frame animation CSS.
- If the required resources are large, use them
Lottie
Program, and then design students with AE animation JSON everywhere, the animation will be restored tosvg/canvas/html
.
Interactive & Interactive Mini-games & Bone Animation:
- For the interactive scene more responsible for or need to make a small game, can be used
PixiJs
Through theWebGL
To render, use hardware resources, greatly improve performance, in terms of compatibility, for not supportedWebGL
The browser can be usedCanvas rendering
toSmooth back
; - If you need to show bone animation, you can pass
PixiJs
The scheme is rendered bySpine
orDragonBones
Output file.