As a front-end developer, our mission is to present the best experience to users on the basis of satisfying 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. Therefore, the front end to achieve dynamic effect of several common ways sorted into this summary, in order to review the old and learn new, such as improper also hope more corrections.

Childhood. PNG

Animation is Childhood

Animation refers to many frames of static picture, with a certain speed (such as 16 per second) continuous playback, the naked eye due to visual residual image illusion, and mistakenly think the picture of the work of activity. — Wikipedia

That’s the definition of animation from Wikipedia. I’m sure every kid with a childhood like mine has played flip books, or even if yours was a little darker, watched cartoons. Well, it’s not a digression, it’s essentially the same as the animation we talked about today, but the presentation or the medium has changed.

Superman vs Saiya.avi

A few basic concepts

A brief introduction to some basic concepts of animation:

Frame: In the animation process, each still picture is a “frame”; Frame rate: The number of still images played per second, expressed in Frame per second or Hertz (Hz); Frame duration: the dwell time of each still image, usually in ms(ms); Frame loss: In an animation with a fixed frame rate, the duration of one frame is longer than the average frame length, resulting in subsequent frames being squeezed and lost;

The animation we see on the display, each frame change is drawn by the system (GPU or CPU). Its maximum drawing frequency is limited by the refresh rate of the monitor (not the graphics card, which is mostly 60Hz or 75Hz).

The higher the frame rate, the less flickering the picture on the screen will be and the more stable it will be. It is not easy for human eyes to detect the flickering sensation caused by the refresh frequency above 75Hz.

implementation

There are usually several main ways we can implement animations on the front end:

  • JavaScript: Change element styles with timer intervals (setTimeout and setIterval), or use requestAnimationFrame;
  • CSS3: Transition and animation;
  • HTML5: Drawing methods provided by HTML5 (Canvas, SVG, WebGL);

Animations.png

requestAnimationFrame

RequestAnimationFrame is a browser interface for timed loops, similar to setTimeout, that redraw a web page frame by frame.

The purpose of this API is to enable a unified refresh mechanism for various web animation effects (DOM animation, Canvas animation, SVG animation, WebGL animation), thus saving system resources, improving system performance, and improving visual effects. By using this API in your code, you tell the browser that you want to perform an animation and have the browser schedule a web page redraw for the next animation frame.

RequestAnimationFrame takes a callback function as an argument. This callback function is called before the browser is redrawn. Since the effect is only one-time, a recursive call is required to achieve continuous action, as shown in the following example:

<div id="demo" style="position:absolute; width:100px; height:100px; background:#ccc; left:0; top:0;" ></div> <script> var demo = document.getElementById('demo'); function render(){ demo.style.left = parseInt(demo.style.left) + 1 + 'px'; } requestAnimationFrame(function(){render(); If (parseInt(demo.style.left) <= 300) requestAnimationFrame(arguments.callee); }); </script>Copy the code

The cancelAnimationFrame method is used to cancel the redraw:

var requestID = requestAnimationFrame(repeatOften);
cancelAnimationFrame(requestID);
Copy the code

The advantages of using requestAnimationFrameAPI are as follows:

  • All DOM operations in each frame are grouped together in a single redraw or reflow, and the redraw or reflow interval closely follows the refresh rate of the display (60 Hz or 75 Hz);
  • There will be no redrawing or reflow in hidden or invisible elements, which of course means less CPU, GPU, and memory usage;

Currently, the major browsers Firefox 23 / IE 10 / Chrome/Safari support this method. You can check if the browser supports the API by using the following method. If not, simulate the deployment of the method yourself.

window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element){ window.setTimeout(callback, 1000 / 60); }; }) ();Copy the code

So, requestAnimationFrame is a performance-optimized setTimeout for animation, but requestAnimationFrame does not specify its own callback time. Instead, the callbacks follow the browser’s built-in refresh rate, which of course achieves the best animation the browser can achieve.

Transition

The transition property in the CSS allows block-level elements to change smoothly over a specified period of time.

transition: property duration timing-function delay;
Copy the code

Specific attribute values are described as follows:

value

describe

transition-property

Specifies the name of the CSS property that sets the transition effect. (None/all/property)

transition-duration

Specifies how many seconds or milliseconds it takes to complete the transition effect.

transition-timing-function

The speed curve specifying the speed effect. (Linear, ease, ease-in, ease-out, ease-in-out, cubic-bezier(n,n,n,n))

transition-delay

Define when transition effects begin.

Animation

Similar CSS also provides an Animation property, but unlike Transition, Animation works on elements instead of style properties, and you can use the concept of keyframes, which should be said to give you more freedom to animate.

grammar

animation: name duration timing-function delay iteration-count direction;
Copy the code

Specific attribute values are described as follows:

value

describe

animation-name

Specifies the name of the KeyFrame to bind to the selector. (Keyframename, None)

animation-duration

Specifies the time, in seconds or milliseconds, to complete the animation.

animation-timing-function

Specifies the speed curve of the animation. (Linear, ease, ease-in, ease-out, ease-in-out, cubic-bezier(n,n,n,n))

animation-delay

Specifies the delay before the animation begins.

animation-iteration-count

Specifies how many times an animation should play.

animation-direction

Specifies whether the animation should take turns playing backwards. (Normal, alternate)

Canvas

< Canvas > is a new element in HTML5 that acts as a container for drawing page graphics and can be used to draw graphics using scripts in JavaScript. For example, it can be used for drawing graphics, making photos, creating animations, and even real-time video processing or rendering. Canvas has the following features:

  • Resolution-dependent, bitmap-based;
  • Event handlers are not supported;
  • Weak text rendering capabilities;
  • Can save the resulting image in.png or.jpg format;
  • Best suited for graphics-intensive games, where many objects are frequently redrawn;

Most Canvas drawing apis are not defined on the element itself, but rather on a “drawing environment” object obtained through the Canvas’s getContext() method. The Canvas API also uses the representation of paths. However, paths are defined by a series of method calls, rather than strings described as letters and numbers, such as calls to beginPath() and arc() methods. Once a path is defined, other methods, such as fill(), operate on that path.

SVG

Scalable Vector Graphics (SVG), short for Scalable Vector Graphics, is used to define vector-based Graphics for networks. SVG uses XML to define images and has the following features:

  • Resolution independent, based on vector graph;
  • Support event handlers;
  • Best for applications with large rendered areas (such as Google Maps);
  • High complexity slows down rendering (any application that overuses the DOM is slow);
  • Not suitable for game applications;

Let’s look at a simple example that draws a circle in SVG:

< SVG XMLNS = "http://www.w3.org/2000/svg" version = "1.1" > < the rect x = "50" y = "20" rx = "20" ry = "20" width = "150" height = "150" style="fill:red; stroke:black; stroke-width:5; Opacity: 0.5 "/ > < / SVG >Copy the code

SVG code starts with a < SVG > element, including an open tag < SVG > and a close tag
. This is the root element. The width and height attributes set the width and height of this SVG document. The Version attribute defines the version of SVG used, and the XMLNS attribute defines the SVG namespace.

SVG’s

is used to create a circle. The Cx and cy attributes define the x and y coordinates of the center of the circle. If these two properties are ignored, the dot is set to (0, 0). The r property defines the radius of the circle.

Here are a few elements in SVG for animation:

: usually placed inside an SVG image element to define the animation process for an attribute of the image element; The: element is also placed inside an image element, which can refer to a predefined animation path, so that the image element moves in the way defined by the path; : The element has more control over the motion and transformation of the graph. It can specify the transformation, scaling, rotation and distortion of the graph. The: element is used in the example above. It is a helper element through which an element such as

can reference an external defined . Let the image elements follow this trajectory;

WebGL

WebGL enables web pages to be 3D rendered in Canvas using OpenGL ES 2.0 API without any plug-in installed in browsers that support HTML < Canvas > tags. WebGL programs consist of JavaScript control code and shader code (rendering code) that is executed in the computer’s graphics processing unit (GPU).

WebGL.png

WebGL is essentially based on a raster API, not a 3D-based API. WebGL only focuses on two aspects, the coordinates of the projection matrix and the color of the projection matrix. The task of using WebGL programs is to achieve WebGL objects with projection matrix coordinates and colors. You can use shaders to do this. The vertex shader provides the coordinates of the projection matrix, and the fragment shader provides the color of the projection matrix.

Kaixin666haoyun </ SVG >Copy the code