react-node-background
Version:
Animated node network background component for React
3 lines (2 loc) • 1.77 kB
JavaScript
import t,{useRef as e,useState as n,useEffect as o}from"react";const a=({nodeCount:a=156,connectionDistance:r=250,nodeSpeed:i=.7,backgroundColor:l="rgba(251, 243, 216, 0.9)",backgroundColorDark:c="rgba(42, 56, 111, 0.9)"})=>{const s=e(null),[d,h]=n(document.documentElement.classList.contains("dark"));return o((()=>{const t=new MutationObserver((t=>{t.forEach((t=>{"class"===t.attributeName&&h(document.documentElement.classList.contains("dark"))}))}));t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]});const e=s.current,n=e.getContext("2d");let o;const m=()=>{e.width=window.innerWidth,e.height=window.innerHeight};m(),window.addEventListener("resize",m);const u=[];for(let t=0;t<a;t++)u.push({x:Math.random()*e.width+50,y:Math.random()*e.height+50,radius:5*Math.random()+2,vx:(Math.random()-.5)*i,vy:(Math.random()-.5)*i,color:`hsla(${360*Math.random()}, 70%, 80%, ${.5*Math.random()+.25})`});const w=()=>{n.clearRect(0,0,e.width,e.height),n.fillStyle=d?c:l,n.fillRect(0,0,e.width,e.height),n.lineWidth=.5;for(let t=0;t<u.length;t++)for(let e=t+1;e<u.length;e++){const o=u[t].x-u[e].x,a=u[t].y-u[e].y,i=Math.sqrt(o*o+a*a);if(i<r){const o=1-i/r;n.strokeStyle=`hsla(${360*Math.random()}, 90%, 80%, ${.5*o})`,n.beginPath(),n.moveTo(u[t].x,u[t].y),n.lineTo(u[e].x,u[e].y),n.stroke()}}u.forEach((t=>{t.x+=t.vx,t.y+=t.vy,(t.x<-50||t.x>e.width+50)&&(t.vx*=-1),(t.y<-50||t.y>e.height+50)&&(t.vy*=-1),n.beginPath(),n.arc(t.x,t.y,t.radius,0,2*Math.PI),n.fillStyle=t.color,n.fill()})),o=window.requestAnimationFrame(w)};return w(),()=>{window.cancelAnimationFrame(o),window.removeEventListener("resize",m),t.disconnect()}}),[d,a,r]),t.createElement("canvas",{ref:s,className:"w-full h-full"})};export{a as default};
//# sourceMappingURL=index.esm.js.map