requestAnimationFrame
http://www.jiawin.com/requestanimationframe-animation-windmill
在以往,我们在网页上制作动画效果的时候,如果是用javascript实现,一般都是通过定时器和间隔来实现的,出现HTML5之后,我们还可以用CSS3 的transitions
和animations
很方便的实现动画,这些技术手段在对于简单的或者对流畅性要求不高的动画不会有什么问题,然而随着用户体验的提高,我们制作的动画效果有了更高的要求,那么对于比较复杂的而且具有较高流畅性的动画效果,用以上的两种方法就有点捉襟见肘了。对于质量较高的动画效果的实现,我们又不想用falsh,那怎么办呢?为解决这个问题,浏览器提供了一个统一帧管理、提供监听帧的API,即requestAnimationFrame
。我们今天就是利用requestAnimationFrame()
函数来实现一个高质量旋转风车的动画效果。
使用优势
一:假如同时进行的n个动画,函数会把原本需要n次reflow和repaint优化成1次,然后交给浏览器进行优化,这样就实现了高质量的动画效果。
二:如果浏览器的某个tab正在运行这样一个动画,然后你切到另一个tab,或者干脆最小化,总之就是你看不见它了,这时浏览器就会停止动画。这将意味着更少的CPU和更少的内存消耗。
http://stackoverflow.com/questions/13522602/when-to-use-requestanimationframe
For many simple modifications of the DOM, this method is overkill. This only becomes useful when you are doing animations when you will be drawing or moving items quickly and need to make sure that the browser repainting is keeping up enough to make it smooth. It will allow you to ensure that every frame you calculate will be drawn to the screen. It also provides a utility for more accurate time measurements to your animations. The first argument is the time at which the paint will occur, so you can ensure that you are where you should be at that moment.
You should not use it when you are doing many simple modifications to the DOM, or things that don't need to be smoothly transitioned. This will be more expensive on your users' computers so you want to limit this to making things smoother in transitions, movements and animations. Forcing a frame redraw is not needed every time you make a change on the page, since the response will be fast enough most of the time you don't need to worry about that extra couple milliseconds between draws.
http://www.ruanyifeng.com/blog/2015/09/web-page-performance-in-depth.html
重新渲染,就需要重新生成布局和重新绘制。前者叫做"重排"(reflow),后者叫做"重绘"(repaint)。
需要注意的是,"重绘"不一定需要"重排",比如改变某个网页元素的颜色,就只会触发"重绘",不会触发"重排",因为布局没有改变。但是,"重排"必然导致"重绘",比如改变一个网页元素的位置,就会同时触发"重排"和"重绘",因为布局改变了。
涉及到帧处理的才能rAF。
http://www.html5rocks.com/zh/tutorials/internals/howbrowserswork/
在发生变化时,浏览器会尽可能做出最小的响应。因此,元素的颜色改变后,只会对该元素进行重绘。元素的位置改变后,只会对该元素及其子元素(可能还有同级元素)进行布局和重绘。添加 DOM 节点后,会对该节点进行布局和重绘。一些重大变化(例如增大“html”元素的字体)会导致缓存无效,使得整个呈现树都会进行重新布局和绘制。