Summary of the implementation of mainstream animation

Source: Internet
Author: User

Article synced to personal blog:benjamin-focus on front-end development and user experience

Related concepts: Draw frequency, screen refresh rate, hardware acceleration, 60fps

Draw frequency:

Each frame change on the page is a system-drawn (GPU or CPU) "Reference browser Rendering Principle". But this kind of drawing is different from the drawing of PC game, its highest drawing frequency is limited to the refresh frequency of the monitor (not the video card), so the highest drawing frequency is only 60 frames per second (frame per second, the following FPS abbreviation), corresponding to the 60Hz of the display. 60fps is an ideal state, in the daily test of page performance, 60fps is also an important indicator, the closer the better.

refresh rate: the speed at which an image is updated on the screen, that is, the number of times the image on the screen appears per second, in Hertz (Hz). The higher the refresh frequency, the smaller the screen flicker, the higher the stability, in other words, the better the protection of vision. Ordinary people's eyes, not easy to detect the flicker of the 75Hz above the refresh rate, so it is best to adjust your display card refresh frequency to more than 75Hz. It is important to note that not all display cards can achieve a refresh rate of more than 70Hz at the maximum resolution (this performance depends on the speed of the RAMDAC on the display card), and the monitor may not be able to meet the requirements due to insufficient bandwidth. The most important factor that affects the refresh rate is the bandwidth of the monitor.

The display bandwidth is the abbreviation for the width of the display video amplifier's passband, which refers to the maximum total number of pixels that the electron gun sweeps on the screen per second, in MHz (megahertz). The larger the value of the bandwidth, the better the display performance.

Hardware acceleration: The hardware has three processors, CPU, GPU, and APU (not the speed processor is the sound processor). They exchange data via the Pci/agp/pcie bus. Today, the GPU is no longer limited to 3D graphics processing, the development of GPU general computing technology has attracted much attention in the industry, it is proved that in floating-point arithmetic, parallel computing and other parts of the calculation, the GPU can provide dozens of times times more than the CPU performance.

What is the relationship between 60Hz and 60fps?

There is no relationship. FPS represents the frequency at which the GPU renders the screen, and Hz indicates how often the display is refreshed. A static picture, you can say that the picture fps is 0 frames per second, but absolutely not say that the screen refresh rate is 0Hz, that is, the refresh rate does not change with the content of the image. The game is good browser, we talk about dropped frames, refers to GPU rendering screen frequency reduction. such as falling to 30fps or even 20fps, but because of the visual persistence principle, we see the picture is still motion and coherence.

PS: The following example runs in a chrome environment

First, CSS animation 1.1 transitions animation

Instance:

<style type= "Text/css" >.animate {width:200px;height:200px;margin:0 auto;border-radius:50%;background-color: #f00; Line-height:200px;border-radius:50%;text-align:center;color: #fff; font-size:20px;}. animate-transition {transition         : Transform 2s linear;-moz-transition    :-moz-transform 2s linear;- Webkit-transition:-webkit-transform 2s linear;-o-transition      :-o-transform 2s linear;}. Animate-transition:hover {cursor:pointer;transform         : rotate (360deg);-moz-transform    : Rotate (360deg);- Webkit-transform:rotate (360deg);-o-transform      : Rotate (360deg);} </style><div class= "Animate animate-transition" >transition animation</div>

View Example Demo

1.2 Keyframes Animation

Keyframes Animation enables more complex animation effects by defining multiple keyframes and defining attribute values for the elements in each keyframe. Instance:

<style type= "Text/css" >.animate-keyframes {-webkit-animation:frames 2s linear infinite;}. animate-keyframes:hover {cursor:pointer;-webkit-animation:none;} @-webkit-keyframes Frames {0% {background-color: #f00;-webkit-transform:rotate (0deg);} 100% {background-color: #f00;-webkit-transform:rotate (360deg);}} </style><div class= "Animate animate-keyframes" >keyframes animation</div>

View Example Demo

1.3 CSS Animations pros and cons

Advantages: Simple, efficient declarative non-dependent and main thread, with hardware acceleration (GPU) Simple control keyframe animation playback and pause disadvantage: cannot dynamically modify or define animation content different animations cannot be synchronized multiple animations cannot be stacked with each other: 1) CSS3 Tran Sition forcing hardware acceleration increases GPU consumption, which in high-load situations will result in a non-smooth operation. This situation is particularly noticeable on mobile devices. (in special cases, such as when data is passed between the main thread of the browser and the layout thread, the resulting bottleneck can also result in a non-fluent). Some CSS properties, such as transform and opacity, are not affected by these bottlenecks. Adobe has carefully summed up these issues here. Detailed please poke transition compatibility problem is a criticism, ie10+ and modern browser, use up will cause a lot of inconvenience. Since transition is not controlled by JavaScript primitives (and is only triggered by JavaScript), the browser does not know how to optimize them synchronously with the JavaScript code that controls these transition. 2) keyframes animation animation curve will be applied to all the changing properties, and handwriting more complex animation, writing is a nightmare.

Two, SVG animation 2.1 instance
<div class= "Animate-svg" ><svg id= "svganimation" ns= "Http://www.w3.org/2000/svg" version= "1.1" width= "200" Height= "" "><g transform=" translate (100,100) "><g><rect width=" "" "height=" "" rx= "100" ry= " "Fill=" Red "transform=" translate ( -100,-100) "></rect><text x=" -60 "y="-0 "font-size=" fill= "" white " >svg animation</text><!--Add ease-in-out and infinite iterations to this Animation and the code--><ani Matetransform attributename= "transform" attributetype= "xml" type= "rotate" from= "0" to= "3s dur=" Indefinite ">svg animation</animatetransform></g></g></svg></div>

View Example Demo

2.2 SVG animation pros and cons

Advantages:

1) vector graphics, unaffected by pixel--svg This feature makes it perform well on different platforms or media, regardless of screen resolution

2) SVG has better support for animations, and its DOM structure can be controlled by its specific syntax or JavaScript, making it easy to implement animations

3) JavaScript can take full control of SVG Dom elements

4) The structure of SVG is XML, its accessibility (Braille, sound reading, etc.), operability, programmability, CSS style can be the triumph of the canvas. In addition, it supports ARIA attributes to make it more powerful.

Disadvantages:

1) DOM is slower than normal graphics, and if its nodes are many and miscellaneous, it is slower.

2) SVG Draw Point Report What, OK, in front of the web game, there is nothing to do, of course, can be combined with Canvas + SVG implementation.

3) animation content cannot be modified dynamically

4) cannot be integrated with HTML content

5) entire SVG as an animated

6) Browser compatibility issues, ie8-and Android 2.3 default browser is not supported SVG

Third, JavaScript animation 3.1 jquery animation

jquery animations are implemented using SetInterval:

Use Case $ ("#div"). Animate ({});//Source JQuery.fx.timer = function (timer) {if (timer () && JQuery.timers.push (timer) & amp;&!timerid) {Timerid = SetInterval (JQuery.fx.tick, JQuery.fx.interval);}}; JQuery.fx.interval = 13;

Why is the animation frame width of jquery 13ms?

How to determine the best "framerate" (setinterval delay) to use in a JavaScript animation loop?

Why does jquery use SetInterval instead of the RAF?

Advantages: Easy to use, low efficiency, good compatibility;

Disadvantages:

1) setinterval multiple intervals may be skipped

2) setinterval multiple intervals may be smaller than expected

3) different browsers have different levels of accuracy:

4) JQuery does not solve the twitching caused by the frequent triggering of Layout.

3.2 Requestanimationframe

Instance:

<style type= "Text/css" >.animate-raf {}.animate-input  {margin-top:10px;text-align:center;} </style><div id= "Animate-raf" class= "animate Animate-raf" >raf animation</div><div class= " Animate-input "><input type=" button "id=" Btn_start "value=" Start "style=" width:100px;height:30px "></div ><script type= "Text/javascript" >var animate_raf   = document.getElementById ("Animate-RAF"), Btn_start = document.getElementById ("Btn_start"), Frameid   = null;function Frame (time) {animate_raf.style['- Webkit-transform '] = ' rotate (' + math.cos (time/1000) *360 + ' deg) '; Frameid = Requestanimationframe (frame);} Bind Eventbtn_start.addeventlistener ("click", Function (event) {var val = this.value;if (val = = = "Start") {Frameid = requ Estanimationframe (frame); this.value = "Pause";} else {this.value = "Start"; Cancelanimationframe (Frameid);}}, False);</script>

View Example Demo

Advantages:

1) You can get notifications and execute apps every time the browser updates the page. As a simple idea, the RAF can execute our function once in each 16.7ms, not much more.

2) Minimizing the consumption of resources, the RAF pauses when the page is toggled or the browser is minimized, and then resumes the animation when the page is focused again.

3) compared to CSS animation has better control, can reasonably reduce the use of the CPU.

Disadvantages:

1) Unable to control the execution time, the execution time is determined by the system according to the screen refresh time

2) Browser compatibility issues, ie10+ and modern browsers, low-version browsers recommend downgrade processing, using SetInterval or settimeout

3.3 Canvas

Advantages:

1) High page rendering performance when drawing 2D graphics

2) page rendering performance is less affected by graphics complexity

3) Rendering performance is only affected by the resolution of the graphics

4) The drawing can be saved directly as a. png or. jpg graphic

5) Best suited for drawing raster images (such as games and irregular geometries), editing pictures, and other pixel-based graphics operations.

Disadvantages:

1) The whole thing is a picture, no matter what you draw on it-there's no DOM node to manipulate.

2) without an animated API, you have to rely on timers and other events to update the canvas

3) Rendering support for text is relatively poor

4) It is difficult to request high accessibility (Braille, voice reading, etc.) pages

5) interface with high interaction requirements (such as many products from TIBCO), it is not recommended to use canvas

3.4 WebGL

WebGL is a 3D drafting standard that allows the combination of JavaScript and OpenGL ES 2.0, and by adding a JavaScript binding to OpenGL ES 2.0, WebGL can be a HTML5 Canvas provides hardware 3D accelerated rendering so that Web developers can display 3D scenes and models more smoothly in the browser with the help of system displays, as well as create complex navigation and data visualizations. Obviously, the WEBGL technology standard eliminates the hassle of developing web-dedicated rendering plugins that can be used to create Web pages with complex 3D structures, and even to design 3D web games.

Browser support:

Internet Explorer 11+

Google Chrome +

Firefox 4+

Opera 12+

Safari 5.1+

3.5 problems

1) Different APIs have different model animations

2) Unnecessary maintenance to support multiple ways to achieve the same thing

3) Web developers need to learn a variety of implementation technologies

4) JavaScript is not easy to set up declarative animations

Iv. Flash Animation (obsolete) v. Web Animations 1.0--a New general purpose animation model

1) W3web Animations 1.0

2) JavaScript implementation of the Web animations API

The Web Animations API provides a single interface for CSS and SVG animations. Designed to make things easier by providing better performance, better control of timelines and playback, a flexible, unified JavaScript programming interface.

Current Status:

Specification at first public working draft:www.w3.org/tr/web-animations

CHROME:CSS Transitions & animations rewritten on top of the Web animations model JavaScript API in development behind A flag

Firefox & safari:started Implementation

Ie:no Public signals

Example one: A simple example

var web_animation_1 = document.getElementById ("web_animation_1"); Web_animation_1.addeventlistener (' Click ', function () {web_animation_1.animate ([{transform: ' Rotate (0deg) '}, {transform: ' Rotate (360deg) '}],{duration:2});}, FALSE);

View Example Demo

Example two: more complex timing

var web_animation_2 = document.getElementById ("web_animation_2"); Web_animation_2.addeventlistener (' Click ', function () {web_animation_2.animate ([{transform: ' Rotate (0deg) '}, {transform: ' Rotate (360deg) '}],{direction: ' Alternate ', duration:1,iterations:infinity,easing: ' Ease-in-out ', Playbackrate:2});}, False);

View Example Demo

Example three: without the syntactic sugar

var web_animation_3 = document.getElementById ("Web_animation_3"); Web_animation_3.addeventlistener (' Click ', function () {var obj = new Animation (web_animation_3,[{transform: ' Rotate (0deg) '}, {transform: ' Rotate (360deg) '}],{ Duration:2});d Ocument.timeline.play (obj);}, False);

View Example Demo

Example four: Parallel animation grouping

var web_animation_4 = document.getElementById ("Web_animation_4"), parItem1 = document.getElementById ("ParItem1"), PARITEM2 = document.getElementById ("parItem2"), ParItem3 = document.getElementById ("ParItem3"); Web_animation_4.  AddEventListener (' click ', function () {var obj = new Pargroup ([New Animation (ParItem1, [{width: ' 0px '}, {width: ' 500px '}], 1), New Animation (parItem2, [{width: ' 0px '}, {width: ' 700px '}], 1), New Animation (ParItem3, [{width: ' 0px '}, {width: ' 200px '}], 1),]) document.timeline.play (obj);}, False);

View Example Demo

Example five: Sequential animation grouping

var web_animation_5 = document.getElementById ("Web_animation_5"), seqItem1 = document.getElementById ("SeqItem1"), SEQITEM2 = document.getElementById ("seqItem2"), SeqItem3 = document.getElementById ("SeqItem3"); web_animation_5.  AddEventListener (' click ', function () {var obj = new Seqgroup ([New Animation (SeqItem1, [{width: ' 0px '}, {width: ' 200px '}], 1), New Animation (seqItem2, [{width: ' 0px '}, {width: ' 300px '}], 1), New Animation (SeqItem3, [{width: ' 0px '}, {width: ' 200px '}], 1),]) document.timeline.play (obj);}, False);

View Example Demo

Example six: Nested grouped animations

var web_animation_6 = document.getElementById ("Web_animation_6"), outerSeqItem1 = document.getElementById (" OuterSeqItem1 "), outerSeqItem2 = document.getElementById (" outerSeqItem2 "), innerParItem1 = document.getElementById (" InnerParItem1 "), innerParItem2 = document.getElementById (" innerParItem2 "), InnerParItem3 = document.getElementById (" InnerParItem3 "); Web_animation_6.addeventlistener (' Click ', function () {var parobj = new Pargroup ([New Animation ( InnerParItem1, [{width: ' 0px '}, {width: ' 300px '}], 1), New Animation (innerParItem2, [{width: ' 0px '}, {width: ' 300px '}], 1) , New Animation (InnerParItem3, [{width: ' 0px '}, {width: ' 300px '}], 1),]), var seqobj = new Seqgroup ([New Animation (Outerseq Item1, [{width: ' 0px '}, {width: ' 200px '}], 1), Parobj,new Animation (outerSeqItem2, [{width: ' 0px '}, {width: ' 200px '}], 1), ]);d Ocument.timeline.play (seqobj);}, False);

View Example Demo

Example Seven: Path animations

var web_animation_7 = document.getElementById ("web_animation_7"); Web_animation_7.addeventlistener (' Click ', function () {var obj = new Animation (web_animation_7,new pathanimationeffect (' M ' + ' C   0 400 100 ' + ' C ' + ' + ' C ' + ', ' auto-rotate ', {duration:2,direction: ' alternate ', easing: ' ea Se-in-out ', Iterations:infinity,});d Ocument.timeline.play (obj);}, False);

View Example Demo

Example eight: Custom animation effects

function Customanimationeffect (timefraction, iteration, target) {web_animation_8.innerhtml = ' timefraction: ' + Timefraction.tofixed (2) + ' \ n ' + '                             iteration: ' + iteration;} var web_animation_8 = document.getElementById ("Web_animation_8"); var obj = new animation (null,    {sample: Customanimationeffect},    {duration:2,direction: ' alternate ', easing: ' Ease-in-out ', Iterations:infinity,}); var Customplayer = Document.timeline.play (obj); Window.addeventlistener (' Slideenter ', function (event) {if (Event.slide = = Customslide) {customplayer.currenttime = 0;}}, False);

View Example Demo

Example nine: a comprehensive example

(function (document) {' Use strict '; var animations = {},player, controls = document.getElementById (' Animate-controls '); Animations.targets = {path:document.getElementById (' path '), BallContainer:document.getElementById (' Animate-ball-container '), Ball:document.getElementById (' Animate-ball ')}; Animations.keyframemove = new Animation (Animations.targets.ballContainer, [{offset:0,transform: ' Translate (0,0) '}, { Offset:1,transform: ' Translate (600,0) '}], {duration:2000}); Animations.keyframespinroll = new Animation (Animations.targets.ball, [{transform: ' Rotate (950deg) '}], {duration:2000 }); Animations.motionpathbounce = new Animation (Animations.targets.ballContainer, New Motionpatheffect ("m25,25" + "a150, 0 0,1 300,0 "+" a75,50 0 0,1 150,0 "+" a35,20 0 0,1 70,0 "+" a2,1 0 0,1 35,0 "+" h45 "), {duration:2500}); Animations.keyframespinbounce = new Animation (Animations.targets.ball, [{transform: ' Rotate (950deg) '}], {duration: 2500}); Animations.animationgrouproll = new Animationgroup ([AnimatioNs.keyframemove, Animations.keyframespinroll], {easing: ' ease-out '}); Animations.animationgroupbounce = new Animationgroup ([Animations.motionpathbounce, Animations.keyframespinbounce], {easing: ' ease-out '}); Controls.addeventlistener (' click ', Function (event) {if (event.target) {var targetelement = Event.target;switch ( targetelement.id) {case ' keyframe-start ':p layer = Document.timeline.play (animations.animationgrouproll); break;case ' Motionpath-start ':p layer = Document.timeline.play (animations.animationgroupbounce); Break;case ' pause ': Player.pause (); Break;case ' Cancel ':p layer.cancel (); Break;case ' Play ':p layer.play (); Break;case ' reverse ': Player.reverse ()}})}) (document);

View Example Demo

Vi. Current compatibility programme

1) page enhancement animations suggest using CSS animations

2) complex animation interaction recommended graceful demotion with RAF and SetInterval or settimeout

3) Recommended animation library velocity.js, Greensock:

Velocity.js is an animated jquery plugin that re-implements the jquery $.animate () method to speed up animation switching. Velocity.js is only 7k in size, it contains not only all the functions of $.animate (), but also includes color switch, transform (transform), loop, ease, CSS switch, scroll function, it is jquery, jquery UI, The best combination of CSS transformations in terms of animation.

Velocity.js supports ie8+, Chrome, Firefox and other browsers, and supports Andriod and iOS.

Velocity.js uses the jquery $.queue () method in its internal implementation, so it is smoother than the $.animate (), $.fade (), and $.delay () methods of jquery, and has a higher performance than the animation properties of CSS.

GREENSOCK:GSAP V12 Platform

Very fast speed: performance is very important, especially on mobile devices. GSAP is continuously optimized to ensure the fast response, efficiency and smoothness of interactive projects, where you can view animation effects testing.

Whimsical strength: Features built into many engines, such as animated colors, Bezier curves, CSS style attributes, flash filters, arrays, and so on, define different callbacks that can be defined by frames or seconds.

Compatibility: Flash,html5,jquery,canvas,css, new browsers, old browsers, Requirejs,easeijs, mobile devices and so on-GSAP can be very well compatible with them, you can choose your familiar tools to use.

JAVASCRIPT,AS3/AS2: Choose the language that's right for you to complete the animation.

Lightweight and scalable: the modular and plug-in structure keeps the core engine lightweight, and the Tweenlite package is very small (basically less than 7kb).

No dependency: Gsap is not built on third-party tools (although it takes jquery as a selector), thus guaranteeing the shortest load times and maximizing performance.

Advanced sequences: Instead of being limited to linear sequences, you can overlap animation sequences, and you can flexibly use minimal code to animate with precise time control.

Good technical support: Through the forum feedback, there will be experts and senior active users to answer questions.

Any object can be animated: Yes, any of the numeric properties of any object can be animated without a predefined attribute, and if these properties (such as colors, filters, non-numeric attributes, etc.) need to be processed, the plug-in can be implemented. If not, we can implement one.

Rewrite management: GSAP helps prevent animation engine conflicts and the setting of advanced options. Easy to learn: documentation, tutorials, examples, learning guides, forums, and a lot of learning resources, very rich.

License: Except for commercial use, GSAP is completely free.

Reference Links:

Web Animations 1.0

CSS would change Module level 1

CSS would change Module Level 1 (Chinese version)

JavaScript high performance animations and page rendering

CSS vs. JS Animation:which is Faster?

CSS animations and transitions performance:looking inside the browser

SVG or Canvas? Сhoosing between the

Exploring the Web animations API

Web Animations by Google

Everything need to Know about the CSS Will-change property

The (80-storey) elevator Pitch

HTML5 Animation Speed Test

Summary of the implementation of mainstream animation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.