Use CSS3 3D planetary operation and Browser rendering principles in detail

Source: Internet
Author: User
Tags chrome developer
Recently into the pit Web animation, so the learning process to record their own share to everyone.

CSS3 3D Planetary Operation Demo page please poke: Demo. (It is recommended to open it with chrome)

The complete code of this article, as well as more CSS3 effects, can be seen on my Github and hopefully you can point to a star.

Well, some people may not be able to open the demo or the page is disorderly, paste a few: (the picture is a bit big, patience wait for a while)

CSS3 3D Planetary operation

A random screenshot of the screen:

It is highly recommended that you click on the Demo page to feel the charm of the CSS3 3D, the image can show something limited after all.

Then, the CSS3 3D Planetary animation production process is no longer detailed, this article focuses on the introduction of Web animation and performance optimization. Detailed CSS3 3D can look back on a blog: "CSS3 advanced" cool 3D rotation perspective. A simple idea:

1. Using the 3D photo wall created by the previous article as a prototype, transformed;

2. The production of each sphere, thinking of a number of methods, eventually using this eclectic way, each of the spheres itself is also a CSS3 3D graphics. Then in the production process using Sass to write CSS can reduce a lot of tedious to write CSS animation process;

3. The Demo uses Javascript to write a mouse to follow the listener event, remove this event, the entire planetary motion animation itself is a pure CSS implementation.

The following will enter the focus of this article, from the perspective of performance optimization of the browser rendering of the principle of display, browser redraw and reflow, animation performance detection optimization, etc.:

The principle of browser rendering and its effect on web animation

The little headline is a bit big, and we know that different browser cores (render engines, Rendering engine) are not the same, for example, the core of the most mainstream Chrome browser is the Blink kernel (in Chrome (28 and later), Opera (15 and later) and Yandex browser use), Firefox is Gecko,ie is Trident, the browser core is responsible for the interpretation of Web page syntax and rendering (display) Web page, different browser cores do not work exactly the same.

So in fact the following will be mainly discussed in the Chrome browser under the rendering principle. Because chrome kernel rendering can be verified more data, for other kernel browser not to be judged, so the discussion below to expand the default is for Chrome browser.

First, I'm going to throw a little conclusion:

Force start of GPU acceleration using the Transform3D API instead of the transform API

Here comes the GPU acceleration, why does the GPU accelerate the 3D transformation? All this must be from the browser bottom of the rendering, the browser renders the process of displaying web pages, commonplace, interview must ask, roughly divided into:

1. Parsing HTML (HTML Parser)

2. Building the DOM tree

3. Render tree construction (render trees)

4. Draw the render tree (Painting)

Found a very classic picture:

This rendering process serves as a basic knowledge and continues to go further down.

When the page is loaded and parsed, it represents a familiar structure in the browser: the DOM (Document Object model). When the browser renders a page, it uses a number of intermediate representations that are not exposed to the developer, the most important of which is the layer.

This layer is the focus of this article to discuss the content:

In Chrome, there are different types of layers: Renderlayer (responsible for DOM subtree), Graphicslayer (responsible for Renderlayer subtree). What we're going to talk about next is the Graphicslayer layer.

The Graphicslayer layer is passed on to the GPU as a texture (texture).

This texture is important here, so,

What is a texture (texture)?

The texture here refers to a term for the GPU: You can think of it as a bitmap image (bitmap image) that moves from the main memory (such as RAM) to the image memory (for example, VRAM in the GPU). Once it's moved to the GPU, you can match it to a grid geometry (mesh geometry) and use textures in Chrome to get chunks of page content from the GPU. By applying textures to a very simple rectangular grid, it is easy to match different positions (position) and deformations (transformation), which is how the 3D CSS works.

It's hard to understand, just look at the example, in chrome, we can see the concept of the graphicslayer-layer described above. In the developer tools, we make the following selections to bring up the show layer borders option:

In a very simple page, we can see the following, this page has only one layer. Blue grids represent tiles, and you can think of them as layers (not layers) that Chrome can pass on to the GPU as a large layer:

Creation of an element's own layer

Because the page above is very simple, so there is no layer, but in a very complex page, for example, we set a 3D CSS property for the element to transform it, we can see when the element has its own layer of what it looks like.

Note The Orange border, which draws the outline of the middle of the view:

When will the create layer be triggered?

The yellow-bordered layer above is graphicslayer, which is very important for our Web animations, and Typically, Chrome draws (paints) into a bitmap before uploading the contents of a layer to the GPU as a texture. If the content does not change, then there is no need to redraw the (repaint) layer.

The point of this is that the time spent on repainting can be used to do something else, such as running JavaScript, which, if drawn for a long time, also causes the animation to fail and delay.

So when does an element trigger the creation of a layer? At this time, the layer is created if any of the following are true:

    • 3D or Perspective transform (Perspective, Transform) CSS properties

    • Using the <video> elements of accelerated video decoding

    • <canvas> elements with 2D context with 3D (WebGL) Context or acceleration

    • Hybrid plugins (such as Flash)

    • Do CSS animations on your own opacity or use an animated transform element

    • Elements that have accelerated CSS filters

    • An element has a descendant node that contains a composite layer (in other words, an element has a child element in its own layer)

    • The element has a sibling element that has a lower z-index and contains a composite layer (in other words, the element is rendered above the composite layer)

Redrawing of layers

For a static web page, the layer will not be changed after the first draw, but for Web animations, the DOM element of the page is constantly changing, and if the content of the layer changes during the transformation, the layer will be redrawn (repaint).

The powerful Chrome Developer tool gives you the tools to see what's been redrawn in the animated page run:

In the older version of Chrome, there is the show Paint rects option, you can see which layers of the page have been redrawn and identified with a red border.

But the new version of Chrome seems to remove this option, and now the option is enable paint flashing, which is also to identify the site dynamic transformation of the place, and identified by a green border.

Look above, you can see a few green boxes in the page, indicating that a redraw has occurred. Note that Chrome does not always redraw the entire layer, it will try to intelligently redraw the invalidated portions of the DOM.

According to the truth, the page has so many animations, repainting should be very frequent, but my planetary animation I only see a few green redraw box, my personal understanding is that one is GPU optimization, and the second is if the entire animation page only one layer, then the use of transform to transform, the page must be redrawn, But using the layered (graphicslayer) technique, which is where the elements that match the situation create layers, the layers created by an element use transform transformations, such as rotate rotation, when the rotation of the layer does not affect the other layers, Then the layer does not have to be redrawn. (Personal opinion, please also correct).

Understanding how layers are redrawn is critical to the performance optimization of Web animations.

What causes failure (invalidation) to be forced to redraw? This question is difficult to answer in detail because of the large number of situations that lead to the failure of the boundary. The most common scenario is to modify the DOM or cause reflow by manipulating CSS styles.

The best way to find the source of the redraw and reflow is to use the developer tools timeline and the Enable paint flashing tool, and then try to figure out where the DOM was modified just before redrawing/re-scheduling.

Summarize

So how does a browser show from DOM elements to the final animation?

    • Browser parsing HTML gets DOM split into multiple layers (graphicslayer)

    • Calculate style results for each layer's node (recalculate style– style recalculation)

    • Generate graphs and locations for each node (layout– reflow and re-layout)

    • Fills each node drawing into the layer bitmap (paint setup and paint– redraw)

    • Layers are uploaded to the GPU as textures (texture)

    • Match multiple layers to create a final screen image on the page (Composite layers– layer reorganization)

A large part of the overhead of Web animation is the redrawing of layers, and the layer-based composite model has a far-reaching impact on rendering performance. When drawing is not required, the cost of a composite operation is negligible, so when trying to debug rendering performance problems, the primary goal is to avoid redrawing the layer. Then this provides the direction for the performance optimization of the animation, reducing the redrawing and reflow of the elements.

Reflow (reflow) and redraw (repaint)

Here we first need to distinguish between two concepts, redraw and reflow.

Reflow (reflow)

When a part (or all) of the render tree is changed because of the size, layout, hiding, etc. of the element, it needs to be rebuilt. This is called reflux (reflow), which is the re-layout (relayout).

Each page needs at least one reflow, which is the first time the page loads. During reflow, the browser invalidates the affected part of the render tree and reconstructs the part of the render tree, and after the reflow is completed, the browser redraws the affected part into the screen, which becomes redrawn.

Redraw (repaint)

When some elements in the render tree need to update properties, these properties only affect the appearance, style of the element, without affecting the layout, such as Background-color. It is called redrawing.

It is important to note that Reflow is bound to cause repainting, and repainting does not necessarily cause reflux.

Obviously, the cost of reflux is even greater, and in simple terms, the return occurs when the element changes its size or position.

When the reflux is triggered:

    • resizing windows (resizing the window)

    • Change font (changing the font)

    • Add or remove a style sheet (Adding or removing a stylesheet)

    • Content changes, such as user input text in input box (content changes, such as a user typing text in

    • An input box)

    • Activates the CSS pseudo-class, for example: hover (the activation of the sibling node pseudo-class in IE) (Activation of CSS pseudo classes such as:hover (in IE the Activation of the pseudo C Lass of a sibling))

    • Operation Class Property (manipulating the class attribute)

    • Script Operation Dom (A script manipulating the DOM)

    • Calculate Offsetwidth and Offsetheight properties (calculating offsetwidth and offsetheight)

    • Set the value of the style attribute (Setting a property of the style attribute)

So for the page, our aim is to minimize the page reflow redraw, a simple chestnut:

The following way will cause reflux reflow two times var newwidth = ap.offsetwidth + 10; Readap.style.width = newwidth + ' px '; Writevar newheight = ap.offsetheight + 10; Readap.style.height = newheight + ' px '; write//below this way better, will only return reflow once var newwidth = ap.offsetwidth + 10; Readvar newheight = ap.offsetheight + 10; Readap.style.width = newwidth + ' px '; Writeap.style.height = newheight + ' px '; Write


The above four sentences, because involved in the offsetheight operation, the browser forced reflow two times, and the following four sentences merged with the offset operation, so reduce the return of a page.

Reducing reflow, redrawing is actually a need to reduce the operation of the rendering tree (merging multiple DOM and style modifications), and reduce the request for some style information, make the best use of the browser's optimization strategy.

Flush Queue

In fact, the browser itself is an optimization strategy, if every Javascript to operate the DOM to make it reflow, the browser may be unbearable. So many browsers will optimize these operations, the browser will maintain a queue, all will cause reflow, redraw operations into the queue, and so on the queue to a certain number of operations or to a certain time interval, the browser will flush the queue, a batch processing. This allows multiple reflow and repainting to become a reflow redraw.

But there are exceptions, because sometimes we need to get some style information exactly, and here's the following:


    • OffsetTop, Offsetleft, offsetwidth, offsetheight



    • Scrolltop/left/width/height



    • Clienttop/left/width/height



    • Width,height



    • Requested getComputedStyle (), or IE's currentstyle


At this point, the browser needs to re-draw the most accurate information immediately, to ensure that the information given to us is accurate, so that the flush queue can be executed ahead of time.

Display:none and Visibility:hidden

Both can hide nodes on the page. The difference is that

    • Display:none The hidden elements do not occupy any space. The various attribute values, such as its width and height, are "lost"

    • Visibility:hidden the hidden element space still exists. It still has a height, width, and other property values

From the point of view of performance, that is the aspect of reflow and repainting,

    • Display:none will trigger reflow (reflux)

    • Visibility:hidden only triggers repaint (redraw), because no location changes are found

They both visibility:hidden better in the optimization because we don't change the display hierarchy already defined in the document because of it.

Effects on child elements:

    • Display:none once the parent node element has applied Display:none, the parent node and its descendant node elements are all invisible, and the display value cannot be displayed, regardless of how the descendant elements are set;

    • Visibility:hidden once the parent node element has applied Visibility:hidden, its descendants will all be invisible. There is, however, a case of hidden "failure". When the descendant elements are applied to the visibility:visible, the descendant elements are revealed.

Performance detection and optimization of animation

Consumption performance Style

Different styles are different in terms of consumption performance, such as Box-shadow, which consumes performance from a rendering perspective, because their drawing code takes too long to execute compared to other styles. This means that if a badly consumed style often needs repainting, you will experience performance problems. Next you have to know that there are no immutable things in today's poorly performing style that may be optimized tomorrow, and there will be differences between browsers.

So the point is that you need to use development tools to identify performance bottlenecks and then try to reduce your browser's workload.

Fortunately, the Chrome browser offers many powerful features that allow us to detect the performance of our animations, and in addition to the above mentioned, we can also check this show FPS meter display page fps information, as well as GPU usage:

Use Will-change to improve rendering performance for page scrolling, animations, and more

Official documentation says this is a feature that is still in the experimental phase, so the syntax and behavior of the feature may change in future versions of the browser.

Examples of Use methods: (the meaning of each value to go through the document)

Will-change:autowill-change:scroll-positionwill-change:contentswill-change:transform        //Example of < Custom-ident>will-change:opacity          //Example of <custom-ident>will-change:left, top        //Example of <animateable-feature>will-change:unsetwill-change:initialwill-change:inherit//example. example{    Will-change:transform;}

Will-change provides a way for web developers to tell the browser how this element will change, so that the browser can prepare for the optimization before the element's attributes really change. This optimization prepares a part of the complex computational work ahead of time, making the response to the page faster and more responsive.

It is important to note that this property is not very easy to use:


    • Do not apply will-change to too many elements: the browser has tried to optimize everything that can be optimized. There are some more powerful optimizations that, if combined with will-change, can consume a lot of machine resources and, if overused, may cause the page to respond slowly or consume a lot of resources.



    • Use sparingly: Typically, when an element reverts to its initial state, the browser discards the optimization work that was done before. However, if the Will-change property is explicitly declared directly in the style sheet, it means that the target element may change frequently, and the browser will save the optimization work longer than before. So the best practice is to switch the value of Will-change before and after the element changes through the script.



    • Do not apply Will-change optimizations prematurely: If your page is not a problem in terms of performance, do not add the Will-change attribute to squeeze the slightest speed. Will-change is designed as a last-resort optimization to try to solve existing performance problems. It should not be used to prevent performance problems. Overuse of will-change can result in a lot of memory usage and lead to more complex rendering processes, as browsers try to prepare for possible changes. This can lead to more serious performance problems.



    • Give it enough work time: This property is used to let the page developer tell the browser which properties may change. The browser can then choose to do some optimization work ahead of time before the change occurs. So it is very important to give the browser a little time to really do the optimization work. When you use it, try to find some way to know what the element might change in advance, and then add the Will-change attribute to it.


Force start of GPU acceleration using the Transform3D API instead of the transform API

The GPU is able to speed up Web animation, which has been mentioned over and over again.

Transform will enable GPU acceleration, such as Translate3d, Scalez and so on, of course, our page may not have 3D transform, but does not mean that we can not enable GPU acceleration, in the non-3D transformation of the page also use 3D transform to operate, calculate is a hack acceleration method. We don't actually need to change the z-axis, but it's a fake pseudo-mock-up to cheat the browser.

Related Article

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.