Bootstrap

Three.js初探:用requestAnimationFrame优化Web动画

Web动画背景

在Web应用中,我们通常使用一个定时器来循环每隔几毫秒移动目标物体一次,来让它动起来,从而形成动画的效果,Js中可以通过定时器 setTimeout 来实现,css3 可以使用 transitionanimation 来实现,html5 在JavaScript API(应用开发接口)出来之前一直是使用的setInterval(function,interval)方法去实现。但是这个方法有问题就是会占用较高的CPU使用率,降低系统的效率。

requestAnimationFrame

通过requestAnimationFrame()方法,浏览器可以优化并行的动画动作,更合理的重新排列动作序列,并把能够合并的动作放在一个渲染周期内完成,从而呈现出更流畅的动画效果。相较于setInterval(function,interval)而言,requestAnimationFrame()方法在这个标签页不可见时,会暂停动画,这会减少CPU,内存的压力,节省电池电量。

使用方法

window.requestAnimFrame = (function() {
   
	return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
		function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
   
			return window.setTimeout(callback, 1000 / 60);
		};
})();

这个反正我看着很费劲,建议结合例子去看,下面是程序里截出来的一部分相关代码。

var step=0;
        renderScene();

        function renderScene() {
   
            stats.update();
            //立方体旋转速度
            cube.rotation.x += 0.05;
            cube.rotation.y += 0.02;
            cube.rotation.z += 0.02;

            step += 0.04;//速度
            //球的运行轨迹
            sphere.position.x = 20 + ( 15 * (Math.cos(step)));
            sphere.position.y = 2 + ( 20 * Math.abs(Math.sin(step)));

            // 告诉浏览器,你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画
            requestAnimationFrame(renderScene);
            renderer.render
;