@genart-api/time-fps-overlay
Version:
GenArtAPI time provider with FPS overlay
2 lines (1 loc) • 1.89 kB
JavaScript
;(()=>{var R=(l,i,t=[])=>({head:()=>l[t[0]],push(r){for(;t.length&&i(l[t[t.length-1]],r);)t.pop();t.push(l.length-1)},shift(){t[0]===0&&t.shift();for(let r=t.length;r-- >0;)t[r]--}}),M=({targetFPS:l=60,period:i=200,width:t=i,height:r=100,style:E="position:fixed;z-index:9999;top:0;right:0;",bg:F="#222",text:C="#fff",fps:v=["#0f0","#ff0","#f00","#306"],fill:k=!1}={})=>{let s,e,x=t/i,$=t>=120,L=performance.now(),b=0,m=0,O=0,u=[],g,d,n=l,T=0,q=!0,w=()=>{let f=[m,b],a=m-O;if(O=m,a<=0)return f;let S=1e3/a,h=u.push(S);g.push(S),d.push(S),h>i&&(h--,T-=u.shift(),g.shift(),d.shift()),T+=S;let{clamp01:P,round:A}=$genart.math;n+=(d.head()*1.1-n)*.1;let y=e.createLinearGradient(0,0,0,s.height);y.addColorStop(P(1-l/n),v[0]),y.addColorStop(P(1-(l-1)/n),v[1]),y.addColorStop(P(1-l/2/n),v[2]),y.addColorStop(1,v[3]),e.fillStyle=F,e.fillRect(0,0,t,r),e[k?"fillStyle":"strokeStyle"]=y,e.setLineDash([]),e.beginPath(),e.moveTo(-1,r);for(let o=0;o<h;o++)e.lineTo(o*x,(1-u[o]/n)*r);k?(e.lineTo((h-1)*x,r),e.closePath(),e.fill()):e.stroke(),e.fillStyle=e.strokeStyle=C,e.setLineDash([1,1]),e.beginPath();for(let o=n>90?30:n>30?15:5,p=A(Math.min(l,n+o/2),o);p>0;p-=o){let c=(1-p/n)*r;e.moveTo(t-80,c),$?(e.lineTo(t-22,c),e.fillText(String(p),t-20,c+1)):e.lineTo(t,c)}return e.stroke(),h>=i&&[[`sma(${i}):`,T/i],["max:",d.head()],["min:",g.head()]].forEach(([o,p],c)=>{let D=r-8-c*12;e.fillText(o,4,D),e.fillText(p.toFixed(1)+" fps",64,D)}),f};return{start(){u=[],g=R(u,(f,a)=>f>=a),d=R(u,(f,a)=>f<=a),n=l*1.2,T=0,s||(s=document.createElement("canvas"),s.width=t,s.height=r,s.id="#FPS",s.setAttribute("style",E),document.body.appendChild(s),e=s.getContext("2d"),e.font="12px sans-serif",e.textBaseline="middle",e.strokeStyle=C,e.setLineDash([1,1]))},next(f){requestAnimationFrame(a=>{q?(L=a,b=0,q=!1):b++,m=a-L,f(m,b),w()})},now(){return[m,b]}}};globalThis.timeProviderFPSOverlay=M;})();