world/static/script/cursor.min.js

2 lines
2.6 KiB
JavaScript

// https://github.com/tholman/cursor-effects/blob/master/src/fairyDustCursor.js
!function(){let t=["#D61C59","#E7D84B","#1B8798"],e=document.body,n=window.innerWidth,i=window.innerHeight;const o={x:n/2,y:n/2},s={x:n/2,y:n/2},h=[],a=[];let c,r,d;const l="*",u=window.matchMedia("(prefers-reduced-motion: reduce)");function f(){if(u.matches)return console.log("This browser has prefers reduced motion turned on, so the cursor did not init"),!1;c=document.createElement("canvas"),r=c.getContext("2d"),c.style.top="0px",c.style.left="0px",c.style.pointerEvents="none",c.style.position="fixed",e.appendChild(c),c.width=n,c.height=i,r.font="21px serif",r.textBaseline="middle",r.textAlign="center",t.forEach(t=>{let e=r.measureText(l),n=document.createElement("canvas"),i=n.getContext("2d");n.width=e.width,n.height=e.actualBoundingBoxAscent+e.actualBoundingBoxDescent,i.fillStyle=t,i.textAlign="center",i.font="21px serif",i.textBaseline="middle",i.fillText(l,n.width/2,e.actualBoundingBoxAscent),a.push(n)}),e.addEventListener("mousemove",p),e.addEventListener("touchmove",v,{passive:!0}),e.addEventListener("touchstart",v,{passive:!0}),window.addEventListener("resize",m),w()}function m(t){n=window.innerWidth,i=window.innerHeight,c.width=n,c.height=i}function v(t){if(t.touches.length>0)for(let e=0;e<t.touches.length;e++)x(t.touches[e].clientX,t.touches[e].clientY,a[Math.floor(Math.random()*a.length)])}function p(e){window.requestAnimationFrame(()=>{o.x=e.clientX,o.y=e.clientY,Math.hypot(o.x-s.x,o.y-s.y)>1.5&&(x(o.x,o.y,a[Math.floor(Math.random()*t.length)]),s.x=o.x,s.y=o.y)})}function x(t,e,n){h.push(new function(t,e,n){const i=Math.floor(30*Math.random()+60);this.initialLifeSpan=i,this.lifeSpan=i,this.velocity={x:(Math.random()<.5?-1:1)*(Math.random()/2),y:.7*Math.random()+.9},this.position={x:t,y:e},this.canv=n,this.update=function(t){this.position.x+=this.velocity.x,this.position.y+=this.velocity.y,this.lifeSpan--,this.velocity.y+=.02;const e=Math.max(this.lifeSpan/this.initialLifeSpan,0);t.drawImage(this.canv,this.position.x-this.canv.width/2*e,this.position.y-this.canv.height/2,this.canv.width*e,this.canv.height*e)}}(t,e,n))}function w(){!function(){if(0!=h.length){r.clearRect(0,0,n,i);for(let t=0;t<h.length;t++)h[t].update(r);for(let t=h.length-1;t>=0;t--)h[t].lifeSpan<0&&h.splice(t,1);0==h.length&&r.clearRect(0,0,n,i)}}(),d=requestAnimationFrame(w)}function g(){c.remove(),cancelAnimationFrame(d),e.removeEventListener("mousemove",p),e.removeEventListener("touchmove",v),e.removeEventListener("touchstart",v),window.addEventListener("resize",m)}u.onchange=(()=>{u.matches?g():f()}),f()}();