平日学习点滴

 

背景:

今天无意中发现一个方法 

 

 
  
  1. window.requestAnimationFrame 

Google之后,就完成了下面得到浏览器每秒帧数的方法。

 

使用:

 
  
  1. showFPS.go(); // go!

 

代码:

 
  
  1. /** 
  2. ** 得到浏览器每秒帧数fps 
  3. **  
  4. ** @Date Mar 13 2013 
  5. **/ 
  6. var showFPS = (function(){ 
  7.     var requestAnimationFrame =  
  8.         window.requestAnimationFrame || //Chromium  
  9.         window.webkitRequestAnimationFrame || //Webkit 
  10.         window.mozRequestAnimationFrame || //Mozilla Geko 
  11.         window.oRequestAnimationFrame || //Opera Presto 
  12.         window.msRequestAnimationFrame || //IE Trident? 
  13.         function(callback) { //Fallback function 
  14.         window.setTimeout(callback, 1000/60); 
  15.         }; 
  16.     var e,pe,pid,fps,last,offset,step,appendFps; 
  17.  
  18.     fps = 0; 
  19.     last = Date.now(); 
  20.     step = function(){ 
  21.         offset = Date.now() - last; 
  22.         fps += 1; 
  23.         if( offset >= 1000 ){ 
  24.         last += offset; 
  25.         appendFps(fps); 
  26.         fps = 0; 
  27.         } 
  28.         requestAnimationFrame( step ); 
  29.     }; 
  30.     //显示fps; 如果未指定元素id,默认<body>标签 
  31.     appendFps = function(fps){ 
  32.         if(!e) e=document.createElement('span'); 
  33.         pe=pid?document.getElementById(pid):document.getElementsByTagName('body')[0]; 
  34.         e.innerHTML = "fps: " + fps; 
  35.         pe.appendChild(e); 
  36.     } 
  37.     return { 
  38.         setParentElementId :  function(id){pid=id;}, 
  39.         go          :  function(){step();} 
  40.     } 
  41. })(); 

 

 

 Vaenow

2013-03-13