Simple Carousel draw--css Animation optimization

Source: Internet
Author: User
Tags pow chrome developer

Preface

Two days ago to a company interview, was asked some small game things. The interviewer mentioned the brush red envelopes and lottery These how to achieve, at that time simply said the next idea, come back to think or say too lightly, do say do not do is bullying, so do a (Demo & source). Starting mode: The finger is sliding on the turntable, the turntable rotates. Here is not the same as the General Lottery program in the background to specify the lottery results, the results are entirely determined by your hand speed (the boss cried ...) )

Interface

The interface is very simple, search for a picture on the Web or directly search a demo on it, of course, self-adaptation is also necessary. Here with the use of REM to achieve adaptive, all size units are used REM, change the HTML node Font-size can be achieved full-screen zoom, here is set when the screen width is less than 420px when the turntable size and screen Kuancheng proportional, when the screen is large in 420px when the turntable size fixed. For more information on REM-adaptive content, here's what to look for: here.

interaction and dynamic efficiency

Most of the demos on the Web are click-to-start, thinking about a different way of interacting, using touch screen swipe to start. It is easy to think of rotating the turntable with a sliding screen speed, which can be slowed down by giving a negative acceleration when turning. Here to pay attention to the user experience, in order to let people have a smooth feeling, the speed of the start must be quite fast, the end of the time to slow down, to create a lottery tension atmosphere. So acceleration is a big, small change that has the same effect as the ease-out in CSS. The code is as follows:

varrotate = document.getElementById (' IMGs '));varSpeed = Vspeed = 0, x0= y0 = T0 = x1 = Y1 = T1 =NULL;(function(){    varLasttime = 0; varVendors = [' ms ', ' Moz ', ' webkit ', ' O '];  for(varx = 0; x < vendors.length &&!window.requestanimationframe; ++x) {Window.requestanimationframe= window[vendors[x]+ ' Requestanimationframe ']; Window.cancelanimationframe= window[vendors[x]+ ' Cancelanimationframe ' | | window[vendors[x]+ ' Cancelrequestanimationframe '];        }; if(!window.requestanimationframe) {Window.requestanimationframe=function(callback, Element) {varCurrtime =NewDate (). GetTime (); varTimetocall = Math.max (0, +-(Currtime-lasttime)); varid = window.settimeout (function() {Callback (Currtime +Timetocall);            }, Timetocall); Lasttime= Currtime +Timetocall; returnID;    };        }; if(!window.cancelanimationframe) {Window.cancelanimationframe=function(ID) {cleartimeout (ID);    }; };}) (); //Setup Requestanimationframe when it was unavailable.Document.addeventlistener (' Touchmove ',function(e) {E.preventdefault ();}); Rotate.addeventlistener (' Touchstart ',function(e) {if(E.touches.length = = 1) {x0= E.targettouches[0].clientx; Y0= E.targettouches[0].clienty; T0=NewDate (). GetTime (); }}); Rotate.addeventlistener (' Touchend ',function(e) {varthat = This, L= 0, Angle= 0, Timerid=NULL; X1= E.changedtouches[0].clientx; Y1= E.changedtouches[0].clienty; T1=NewDate (). GetTime (); L= Math.sqrt (Math.pow (x1-x0,2) + Math.pow (y1-y0,2)); speed= l/(t1-t0) *20;if(Speed < 10)return; Vspeed= 0.5; varRoll =function() {angle+=Speed ; That.style.transform= ' Rotatez (' + angle + ' deg) '; Switch(true){             CaseSpeed <-0.3: Window.cancelanimationframe (Timerid); return;  CaseSpeed < && vspeed > 0.1: Speed-=Vspeed; Vspeed-= 0.03;  Break; default: Speed-=Vspeed;  Break; } Timerid=window.requestanimationframe (roll);    }; Roll ();});
View Code

Here the animation is also H5 requestanimationframe to achieve, for the browser does not support Requestanimationframe is also compatible.

Programming is quite simple, the difficulty is the adjustment of parameters, to adjust the speed control of the entire rotation cycle can not be too long, and the most troublesome should be the last deceleration phase of the acceleration adjustment. The final stage is too fast, there is no tense atmosphere, too slow and will have the feeling of lag, especially in the domestic mobile browser performance more obvious.

Performance Optimization

Before the performance optimization, in the domestic mobile browser is simply blind eye, optimization is necessary.

General Practice: layering, dynamic elements separated from static elements, that is, the turntable absolute positioning, a separate layer, so that the dynamic element changes will not affect the layout of static elements, reduce repainting. This optimization is very basic, the time to write the page has been implemented, the problem is not visible here. In addition, I have been told to use the Css3d transformation method to force the GPU rendering page to improve performance, but the code I have written ' Rotatez () ', should have turned on the hardware rendering, do not know where the problem, how to solve. Fantasy is useless, quickly with the chrome developer test a bit:

You can see the data is actually quite good, the script, rendering and drawing time is more reasonable, but the problem will be where? Of course, the domestic browser, how to optimize it? Then use Chrome's rendering testing tool to see it. Open in the way:

The first item can detect the drawing refresh (redraw) of the page, the second item shows the layer boundary, and the third item shows FPS (frame per second,fps, framerate), which is a few key concerns. Because this is a single page application, the following scrolling problem detection and media emulation are skipped. After startup, this is the following:

The front green matte represents the redraw area, surrounded by a circle of Brown to represent the render layer, and when you start the animation, you can see that the carousel elements are constantly redrawn when you draw the animation, which should be the key to the problem. But how to solve it? Many articles refer to the following two styles when describing the use of GPU rendering:

backface-visibility:hidden;perspective:1000;

After trying to use these two sentences, the effect appears immediately, and the green redraw frame is no longer present when rotating:

Back to a home-made mobile browser test, and finally no kind of life can not turn up feeling, feel with the original application almost, in fact, the native application is nothing but GPU rendering, when the Web to invoke these underlying words, the performance difference will not be very large. In fact, there is a perspective:1000 in the following sentence; Is redundant, set such a large perspective distance to reduce the 3D effect, reducing the amount of computation, and turntable rotation is not 3D effect, so here is no effect.

the main Backface-visibility:hidden function. Backface is the back of the element, the elements and the hospital's X-ray film, both sides can see. Hide the back of the meaning is to turn around is blank, nothing. If you do not set this, the browser will be rendered even on the back of the object. Since the turntable element is also superimposed on the pointer element, if you do not specify the hidden back, then the browser will be the range of the carousel cover to redraw, for example, I rotate around the X or Y axis, since the drawing of the turntable and draw a pointer, it must be to redraw this large chunk of the page. As for why the rendering layer is not redrawn after hiding the back, this may be related to the browser's rendering strategy, where the browser should redraw the desired layer according to the optimal solution, the invariant layer remains, and the final composition algorithm. This piece I also do not know very much, these are only my personal understanding, has the improper place to be sure to correct!


PS: Follow-up discovery as long as set the Backface-visibility:hidden, do not need to turn on the GPU, directly with 2D rotation can also get very good results!

Grandpa Deng is right, practice is the only standard to test the truth!

Resources:

1) Accelerated Rendering in chrome:http://www.html5rocks.com/en/tutorials/speed/layers/

2) App Performance Validation: https://developer.mozilla.org/en-US/Apps/Fundamentals/Performance/App_performance_validation

3) freed GPU CSS3 animation acceleration: http://www.cnblogs.com/sunshq/p/4878019.html

4) Web Animation CSS3 3D Planetary Operation && Browser rendering principle: http://www.cnblogs.com/coco1s/p/5439619.html#3420358

5) Web animations on large screens:https://developer.mozilla.org/zh-cn/docs/mozilla/firefox_os_for_tv/web_ Animations_on_large_screen

above, The code word is not easy, likes the ha conveniently.

(Photo source: small weeks)

Original articles, reproduced please specify the source! This article link: http://www.cnblogs.com/qieguo/p/5481522.html

Simple Carousel draw--css Animation optimization

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.