UNPKG

@genart-api/time-fps-overlay

Version:

GenArtAPI time provider with FPS overlay

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