Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Vyasdev217/07b0a36f7d12e820ac8b25911345a51c to your computer and use it in GitHub Desktop.
Save Vyasdev217/07b0a36f7d12e820ac8b25911345a51c to your computer and use it in GitHub Desktop.
Representation of mobile nodes' wireless mesh network. Used as background animation of vyasdev.net
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Mobile node mesh network</title>
<style>
html,body{margin:0;padding:0;overflow:hidden;height:100%;font-family:sans-serif}
canvas{position:fixed;top:0;left:0;left:0;right:0;/*z-index:-1*/}
</style>
</head>
<body>
<canvas id="bg"></canvas>
<script>
const c=document.getElementById("bg"),ctx=c.getContext("2d");
let w,h,ants=[];
function resize(){w=window.innerWidth;h=window.innerHeight;c.width=w;c.height=h}
window.addEventListener("resize",resize);
resize();
function getRandomHexColor() {
const randomColor = Math.floor(Math.random() * 16777215).toString(16);
return `#${randomColor.padStart(6, '0')}`;
}
for(let i=0;i<150;i++)ants.push({x:Math.random()*w,y:Math.random()*h,vx:(Math.random()-.5)*1,vy:(Math.random()-.5)*1, color: getRandomHexColor()});
function draw(){
ctx.clearRect(0,0,w,h);
for(let i=0;i<ants.length;i++){
let a=ants[i];
a.x+=a.vx;
a.y+=a.vy;
if(a.x<0||a.x>w)a.vx*=-1;
if(a.y<0||a.y>h)a.vy*=-1;
ctx.beginPath();
ctx.arc(a.x,a.y,5,0,2*Math.PI);
ctx.fillStyle=a.color;
ctx.fill();
for(let j=i+1;j<ants.length;j++){
let b=ants[j],dx=a.x-b.x,dy=a.y-b.y,dist=Math.sqrt(dx*dx+dy*dy);
if(dist<100){
ctx.beginPath();
ctx.moveTo(a.x,a.y);
ctx.lineTo(b.x,b.y);
ctx.strokeStyle="rgba(0,0,0,"+(1-dist/100)+")";
ctx.stroke()
ants[j].color = ants[i].color;
ctx.arc(a.x,a.y,5,0,2*Math.PI);
ctx.fillStyle=ants[j].color;
}
}
}
requestAnimationFrame(draw)
}
draw();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment