-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpruner.min.js
1 lines (1 loc) · 1.53 KB
/
pruner.min.js
1
function imagePruner(){let e=[...document.querySelectorAll("[data-pruner]")],r={},o=e=>r[e]||(r[e]=new Promise((r,o)=>{let a=new Image;a.crossOrigin="ANON",a.onload=()=>r(a),a.onerror=()=>o(e),a.src=e})),a=(e,r,o,a)=>e*o>1920||r*a>1080?.5:1,t=async(e,r,t)=>{let{name:n,tile:l,scale:i="1 0",path:s="",roi:d,imageExtension:c="webp"}=JSON.parse(e.dataset.pruner);if(!l||!n)return;let[f,m]=l.split(" ").map(Number),[u,g]=i.split(" ").map(Number),$=r<=g,{width:_,height:p}=await o(`${s}${n}-1.${c}`),w=Math.round(_*($?u:1)),h=Math.round(p*($?u:1)),E=a(w,h,f,m),b=Math.round(w*E),v=Math.round(h*E),L=Math.min(Math.ceil(r/b),f),x=Math.min(Math.ceil(t/v),m),y=document.createElement("canvas");y.width=L*b,y.height=x*v;let A=y.getContext("2d");A.imageSmoothingEnabled=!1,e.src="";let I=(e,r,o)=>Math.max(r,Math.min(e,o)),N=I(d?Math.floor((d-1)/f)-Math.floor(x/2):Math.floor(m/2)-Math.floor(x/2),0,m-x),O=I(d?(d-1)%f-Math.floor(L/2):Math.floor(f/2)-Math.floor(L/2),0,f-L);(await Promise.all(Array(x*L).fill().map((e,r)=>{let a=N+Math.floor(r/L),t=O+r%L;return a<m&&t<f?o(`${s}${n}-${a*f+t+1}.${c}`):null}))).forEach((e,r)=>{e&&A.drawImage(e,r%L*b,Math.floor(r/L)*v,b,v)}),e.src=y.toDataURL("image/webp")},n,l=0,i=0,s=()=>{let r=innerWidth,o=innerHeight;(r!==l||o!==i)&&(l=r,i=o,e.forEach(e=>t(e,r,o)))},d=(...e)=>{clearTimeout(n),n=setTimeout(()=>s(...e),200)},c=new IntersectionObserver(e=>e.forEach(e=>{e.isIntersecting&&(d(),c.unobserve(e.target))}));window.addEventListener("load",d),e.forEach(e=>c.observe(e)),window.addEventListener("resize",d)}window.onload=imagePruner;