const canvas = document.getElementById("particles");
const ctx = canvas.getContext("2d");

let w = canvas.width = window.innerWidth;
let h = canvas.height = window.innerHeight;

window.addEventListener("resize",()=>{
  w = canvas.width = window.innerWidth;
  h = canvas.height = window.innerHeight;
});

class Particle{
  constructor(){
    this.x=Math.random()*w;
    this.y=Math.random()*h;
    this.size=Math.random()*3+1;
    this.vx=(Math.random()-0.5)*1.2;
    this.vy=(Math.random()-0.5)*1.2;
    this.color=Math.random()>.5?"#0097fc":"#ff6a00";
  }
  draw(){
    ctx.beginPath();
    ctx.arc(this.x,this.y,this.size,0,Math.PI*2);
    ctx.fillStyle=this.color;
    ctx.fill();
  }
  update(){
    this.x+=this.vx;
    this.y+=this.vy;
    if(this.x<0||this.x>w) this.vx*=-1;
    if(this.y<0||this.y>h) this.vy*=-1;
  }
}

const particles=[];
for(let i=0;i<120;i++) particles.push(new Particle());

function connect(){
  for(let a=0;a<particles.length;a++){
    for(let b=a;b<particles.length;b++){
      const dx=particles[a].x-particles[b].x;
      const dy=particles[a].y-particles[b].y;
      const d=Math.sqrt(dx*dx+dy*dy);
      if(d<120){
        ctx.strokeStyle="rgba(0,151,252,.2)";
        ctx.lineWidth=1;
        ctx.beginPath();
        ctx.moveTo(particles[a].x,particles[a].y);
        ctx.lineTo(particles[b].x,particles[b].y);
        ctx.stroke();
      }
    }
  }
}

(function animate(){
  ctx.clearRect(0,0,w,h);
  particles.forEach(p=>{p.update();p.draw();});
  connect();
  requestAnimationFrame(animate);
})();