In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the knowledge of "what is the principle of CSS3 3D planet operation and browser rendering". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Effect diagram of CSS3 3D planetary operation
Another screenshot was taken at random:
It is strongly recommended that you click on the Demo-CSS3 3D Planetary Operation [2] page to feel the charm of CSS3 3D. After all, there is a limit to what the picture can show.
Then, the production process of this CSS3 3D planetary motion animation will not be described in detail, and this article will focus on the introduction of Web animation and performance optimization. For a detailed CSS3 3D, you can read back to the previous blog: [CSS3 Advanced] cool 3D rotation perspective [3]. Simple ideas:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Using the 3D photo wall made in the previous article as the prototype, it is transformed.
There are many ways to make each sphere, and finally this compromise is used, and each sphere itself is a CSS3 3D figure. Then using Sass to write CSS in the production process can reduce a lot of tedious process of writing CSS animation.
Demo has written a mouse-following listening event using Javascript. Without this event, the entire planetary motion animation itself is implemented in pure CSS.
The following will enter the focus of this article, from the perspective of performance optimization, we will talk about the principle of browser rendering and display, browser redrawing and rearrangement, animation performance detection and optimization, and so on:
The principle of browser rendering and its influence on web Animation
The subtitle is a bit big, and we know that the kernel of different browsers (rendering engine, Rendering Engine) is different. For example, the kernel of the most mainstream chrome browser is the Blink kernel (used in Chrome (28 and later), Opera (15 and later) and Yandex), and Firefox is Gecko,IE and Trident.
The browser kernel is responsible for interpreting the web page syntax and rendering (displaying) the web page. Different browser kernels do not work exactly the same.
So in fact, the following will mainly discuss the principle of rendering under the chrome browser. Because there is a lot of verifiable data in chrome kernel rendering, and browsers in other kernels dare not jump to conclusions, the discussion below is for chrome browsers by default.
First of all, I would like to draw a conclusion:
Use transform3d api instead of transform api to force GPU acceleration to start
Here we talk about GPU acceleration. Why can GPU accelerate 3D transformations? All this must start with the rendering at the bottom of the browser. The process of rendering and displaying the web page by the browser is a clich é and must be asked for an interview, which can be roughly divided into:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Parsing HTML (HTML Parser)
Build a DOM tree (DOM Tree)
Render Tree Construction (Render Tree)
Draw a render tree (Painting)
Found a very classic picture:
Browser rendering page proc
As a basic knowledge, this rendering process continues to go further.
When the page is loaded and parsed, it represents a familiar structure in the browser: DOM (Document Object Model, document object model). When a browser renders a page, it uses many intermediate representations that are not exposed to developers, the most important of which is the layer.
This layer is the focus of this article:
In Chrome, there are different types of layers: RenderLayer (responsible for the DOM subtree) and GraphicsLayer (the subtree responsible for RenderLayer). What we will discuss next is the GraphicsLayer layer.
The GraphicsLayer layer is uploaded to GPU as a texture.
This texture here is very important, so
What is a texture (texture)?
Texture here refers to a term for GPU: think of it as a bitmap image (bitmap image) that is moved from main memory (such as RAM) to image memory (such as VRAM in GPU). Once it is moved into GPU, you can match it to a mesh geometry (mesh geometry) and use textures in Chrome to get large chunks of page content from GPU.
You can easily match different positions (position) and deformations (transformation) by applying textures to a very simple rectangular mesh, which is how 3D CSS works.
It's hard to understand, but let's just look at the example. In chrome, we can see the concept of GraphicsLayer-layer mentioned above. In the developer tool, we make the following choices to call up the show layer borders option:
On a very simple page, we can see that this page has only one layer as shown below. The blue grid represents tile, which you can think of as layer units (not layers), and Chrome can upload them to GPU as part of a large layer:
The creation of the element's own layer
Because the above page is very simple, there are no layers generated, but in very complex pages, for example, if we set a 3D CSS attribute to transform the element, we can see what it looks like when the element has its own layer.
Notice the orange border, which outlines the middle layer of the view:
When is the creation layer triggered?
The layer framed in yellow in the above diagram is GraphicsLayer, which is very important for our Web animation. Usually, Chrome will paint the contents of a layer into a bitmap before uploading it to GPU as a texture. If the content does not change, there is no need to repaint the layer.
The point is that the time spent on redrawing can be used to do other things, such as running JavaScript, which can cause animation failures and delays if it takes a long time to draw.
So when does an element trigger the creation of a layer? For now, layers are created if any of the following conditions are met:
3D or perspective transformation (perspective, transform) CSS attribute
Using accelerated video decoding
Elements with 3D (WebGL) context or accelerated 2D context
Mixed plug-ins (such as Flash)
Animate your own opacity or use an animated transformation element
Elements with 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 with a lower z-index and contains a composite layer (in other words, the element is rendered on top of the composite layer)
Redrawing of layer
For static Web pages, the layer will not be changed after being drawn for the first time, but for Web animation, the DOM elements of the page are constantly changing, and if the content of the layer changes during the transformation process, the layer will be redrawn (repaint).
The powerful chrome developer tool provides tools to see what has been redrawn while the animation page is running:
In the old version of chrome, there was an option of show paint rects to see which layers of the page had been redrawn and marked with a red border.
But the new version of chrome seems to have removed this option, and now the option is enable paint flashing, which also identifies where the site changes dynamically and with a green border.
Looking at the diagram above, you can see that there are several green boxes on the page, indicating that a redrawing has taken place. Note that Chrome does not always redraw the entire layer, it will try to intelligently redraw the failed parts of the DOM.
According to reason, there are so many animations on the page, redrawing should be very frequent, but in my planetary animation above, I only see a few green redraw frames. My personal understanding is that one is GPU optimization, and the other is that if the whole animation page has only one layer, then the page must be redrawn if transform is used for transformation, but it uses GraphicsLayer technology, that is, the elements that match the situation above are created separately. Then the layer created by an element uses transform transformations, such as rotate rotation, and the rotation transformation of that layer does not affect other layers, so the layer does not necessarily need to be redrawn. (in your personal opinion, please make corrections.)
Understanding the redrawing of layers is critical to optimizing the performance of Web animation.
What caused the failure (invalidation) and forced the redrawing? This question is difficult to answer in detail because there are a large number of cases that lead to boundary failure. The most common situation is to modify the DOM or cause rearrangement by manipulating the CSS style.
The best way to find the root causes of redrawing and rearrangement is to use the developer tool's timeline and the enable paint flashing tool, and then try to find out where the DOM was modified just before the redraw / rearrangement.
Summary
So how does the browser go from the DOM element to the final animation?
After parsing HTML to get DOM, the browser splits it into multiple layers (GraphicsLayer)
Calculate the style results for the nodes of each layer (Recalculate style-- style recalculation)
Generate graphics and locations for each node (Layout-- reflow and relayout)
Fill each node drawing into the layer bitmap (Paint Setup and Paint-- redraw)
Upload layers to GPU as texture
Match multiple layers to the page to generate the final screen image (Composite Layers-- layer reorganization)
A large part of the overhead of Web animation lies in the redrawing of layers, and the layer-based composite model has a far-reaching impact on rendering performance. The overhead of compositing operations is negligible when you don't need to paint, so the primary goal when trying to debug rendering performance problems is to avoid layer repainting. Then this provides a direction for the performance optimization of animation, reducing the redrawing and reflux of elements.
Reflow (reflow) and redraw (repaint)
First of all, we need to distinguish between two concepts, redrawing and reflux.
Reflux (reflow)
When some (or all) of the render tree (render Tree) needs to be rebuilt due to changes in element size, layout, hiding, and so on. This is called reflow, that is, relayout.
Each page needs to be reflowed at least once, when the page is first loaded. When reflux, the browser invalidates the affected part of the render tree and reconstructs the part of the render tree. When the reflow is complete, the browser will redraw the affected part to the screen, which is called redrawing.
Redraw (repaint)
When some elements in render tree need to update attributes, and these attributes only affect the appearance and style of the element, but not the layout, such as background-color, it is called redrawing.
It is worth noting that reflow will inevitably lead to repainting, while repainting will not necessarily cause reflow.
Obviously, reflow is more expensive, and in short, reflux occurs when an operation element causes an element to change its size or position.
When does backflow trigger:
Resize the window (Resizing the window)
Change font (Changing the font)
Add or remove style sheets (Adding or removing a stylesheet)
Content changes, such as user typing text (Content changes, such as a user typing text in) in the input box
An input box)
Activate CSS pseudo-class, for example: hover (activation for sibling pseudo-class in IE) (Activation of CSS pseudo classes such as: hover (in IE the activation of the pseudo class of a sibling))
Manipulate the class property (Manipulating the class attribute)
Script Action DOM (A script manipulating the DOM)
Calculate offsetWidth and offsetHeight properties (Calculating offsetWidth and offsetHeight)
Set the value of the style property (Setting a property of the style attribute)
So for the page, our goal is to minimize the reflow of the page, a simple chestnut:
/ / the following way will cause reflow to return twice var newWidth = aDiv.offsetWidth + 10; / / Read aDiv.style.width = newWidth + 'px'; / / Write var newHeight = aDiv.offsetHeight + 10; / / Read aDiv.style.height = newHeight +' px'; / / Write / / the following is better, var newWidth = aDiv.offsetWidth + 10; / / Read var newHeight = aDiv.offsetHeight + 10 only once / / Read aDiv.style.width = newWidth + 'px'; / / Write aDiv.style.height = newHeight +' px'; / / Write
In the above four sentences, because the offsetHeight operation is involved, the browser forces reflow twice, while the following four sentences combine the offset operation, so the backflow of the page is reduced.
To reduce reflux and redraw is to reduce the operation of the render tree (merging multiple DOM and style changes), and reduce the request for some style information, so as to make good use of the browser's optimization strategy.
Flush queue
In fact, the browser itself has an optimization strategy, and if every Javascript manipulates the DOM to redraw it, the browser may not be able to stand it. Therefore, many browsers will optimize these operations. Browsers will maintain a queue and put all operations that will cause reflow and redrawing into this queue. When the number of operations in the queue reaches a certain number or at a certain time interval, the browser will flush the queue for batch processing. In this way, many times of repainting and redrawing will be turned into a redrawing.
But there are exceptions, because sometimes we need to get some style information precisely, as follows:
OffsetTop, offsetLeft, offsetWidth, offsetHeight
ScrollTop/Left/Width/Height
ClientTop/Left/Width/Height
Width,height
Requested getComputedStyle (), or currentStyle of IE
At this time, in order to feedback the most accurate information, the browser needs to redraw the flow immediately to ensure that the information given to us is accurate, so it may cause the flush queue to be executed ahead of time.
Display:none and visibility:hidden
Both can hide nodes on the page. The difference is that
The hidden elements of display:none do not take up any space. Its width, height and other attribute values will be "lost".
The element space hidden by visibility:hidden still exists. It still has attribute values such as height, width, etc.
From a performance point of view, it is the aspect of reflow and redrawing.
Display:none will trigger reflow (backflow)
Visibility:hidden will only trigger repaint (redraw) because no position change is found.
The visibility:hidden of both of them will look better in optimization, because we will not change the display hierarchy already defined in the document because of it.
Impact on child elements:
Display:none once display:none is applied to the parent node element, the parent node and its descendant node elements are not visible, and no matter how their descendant elements set the display value, they cannot be displayed
Visibility:hidden once the parent node element has visibility:hidden applied, its descendants will be completely invisible. However, there are hidden "failures". When its descendant element applies visibility:visible, then this descendant element will appear again.
Performance testing of Animation and Optimization of performance consumption style
Different styles are different in terms of performance consumption. For example, box-shadow is very performance-consuming from a rendering perspective because their drawing code takes too long to execute compared to other styles. That is to say, if a performance-consuming style often needs to be redrawn, then you will encounter performance problems. Second, you should know that nothing remains the same. Styles that perform poorly today may be optimized tomorrow, and there are differences between browsers.
So the key is that you use development tools to identify performance bottlenecks and then try to reduce the browser's workload.
Fortunately, the chrome browser provides many powerful features that allow us to test our animation performance. In addition to the above, we can also display the FPS information of the page and the utilization rate of GPU by checking the following show FPS meter:
Using will-change to improve the rendering performance of page scrolling, animation, etc.
Official documentation says [4] that this is a feature that is still in the experimental stage, so the syntax and behavior of the feature may change in future browsers.
Will-change provides a way for web developers to tell browsers how the element will change, so that browsers can prepare for optimization before the element attributes actually change. This optimization can prepare part of the complex calculation work in advance and make the response of the page more fast and sensitive.
Take a look at Can i Use-will-change [5], updated 2021-03-31:
Example of usage: (specific to the meaning of each value, to flip through the document)
Will-change: auto will-change: scroll-position will-change: contents will-change: transform / / Example of will-change: opacity / / Example of will-change: left, top / / Example of two will-change: unset will-change: initial will-change: inherit / / example {will-change: transform;}
It is worth noting that it is not easy to use this attribute well:
Don't apply will-change to too many elements: browsers have tried their best to optimize everything that can be optimized. There are some more powerful optimizations that, when combined with will-change, can consume a lot of machine resources, and if overused, can lead to slow page response or very resource consumption.
Moderate use: usually, when the element returns to its original state, the browser discards the previous optimization work. But if you explicitly declare the will-change attribute directly in the stylesheet, the target element may change frequently, and the browser will save the optimization longer than before. So the best practice is to use scripts to switch the value of will-change before and after the element changes.
Don't apply will-change optimization too early: if your page has no performance problems, don't add the will-change attribute to squeeze a little bit of speed. Will-change was originally designed as a last resort to try to solve existing performance problems. It should not be used to prevent performance problems. Excessive use of will-change can result in a large memory footprint and a more complex rendering process, as browsers try to prepare for possible changes. This can lead to more serious performance problems.
Give it enough working 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 in advance before the change occurs. So it's very important to give browsers some time to actually do these optimizations. When you use it, you need to try to find some ways to know in advance how the element may have changed, and then add the will-change attribute to it.
GPU can speed up Web animation, which has been mentioned repeatedly above.
3D transform will enable GPU acceleration, such as translate3D, scaleZ, etc. Of course, our pages may not have 3D transformation, but that does not mean we can not enable GPU acceleration, in non-3D transformation pages also use 3D transform to operate, can be regarded as a hack acceleration method. We don't really need a change in the z-axis, but we still pretend to declare it to deceive the browser.
References:
Rendering: repaint, reflow/relayout, restyle [6]
Scrolling Performance [7]
MDN--will-change [8]
How (not) to trigger a layout in WebKit [9]
High Performance Animations [10]
Accelerated Rendering in Chrome [11]
Making 3D rotating sphere by CSS3 [12]
This is the end of the content of "what is the principle of CSS3 3D Planet Operation and browser rendering". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.