cm-ricochet
Version:
Creates a ricochet effect for an element inside a container.
2 lines (1 loc) • 2.29 kB
JavaScript
;var R=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var k=(i,e)=>{for(var m in e)R(i,m,{get:e[m],enumerable:!0})},B=(i,e,m,v)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of U(e))!j.call(i,s)&&s!==m&&R(i,s,{get:()=>e[s],enumerable:!(v=O(e,s))||v.enumerable});return i};var G=i=>B(R({},"__esModule",{value:!0}),i);var J={};k(J,{startRicochet:()=>H});module.exports=G(J);var H=({container:i,item:e,horizontalSpeed:m=370,verticalSpeed:v=200,initialDirection:s,onHitBorder:g,onHitLeft:L,onHitRight:M,onHitTop:C,onHitBottom:I})=>{let F=0,x=0,o,r,d=performance.now(),A=performance.now(),a=!1,l,u,q=t=>{let n=i.getBoundingClientRect(),c=e.getBoundingClientRect(),T=c.top-n.top,w=c.left-n.left,E=T+c.height,P=w+c.width;if(t==="top")return T<=0;if(t==="bottom")return E>=n.height;if(t==="left")return w<=0;if(t==="right")return P>=n.width},f=t=>{if(a)return;let n=(t-A)/1e3;if(A=t,x-=m*n,e.style.left=x+"px",q("left")){g?.(),L?.(),o=requestAnimationFrame(b),l=b;return}o=requestAnimationFrame(f),l=f},b=t=>{if(a)return;let n=(t-A)/1e3;if(A=t,x+=m*n,e.style.left=x+"px",q("right")){g?.(),M?.(),o=requestAnimationFrame(f),l=f;return}o=requestAnimationFrame(b),l=b},h=t=>{if(a)return;let n=(t-d)/1e3;if(d=t,F-=v*n,e.style.top=F+"px",q("top")){g?.(),C?.(),r=requestAnimationFrame(p),u=p;return}r=requestAnimationFrame(h),u=h},p=t=>{if(a)return;let n=(t-d)/1e3;if(d=t,F+=v*n,e.style.top=F+"px",q("bottom")){g?.(),I?.(),r=requestAnimationFrame(h),u=h;return}r=requestAnimationFrame(p),u=p},z=()=>{a||(a=!0,cancelAnimationFrame(o),cancelAnimationFrame(r))},D=()=>{a&&(a=!1,A=performance.now(),d=performance.now(),o=requestAnimationFrame(l),r=requestAnimationFrame(u))},y=()=>{document.visibilityState==="hidden"?z():document.visibilityState==="visible"&&D()},V=()=>{i.style.position="relative",e.style.position="absolute";let t={"bottom-left":[f,p],"bottom-right":[b,p],"top-right":[b,h],"top-left":[f,h]},[n,c]=t[s??"bottom-right"];l=n,u=c,o=requestAnimationFrame(n),r=requestAnimationFrame(c)};return document.addEventListener("visibilitychange",y),V(),()=>{cancelAnimationFrame(o),cancelAnimationFrame(r),document.removeEventListener("visibilitychange",y)}};0&&(module.exports={startRicochet});