JSFiddle - React, Tailwind, and code Playground

by Umair Rafiq

HTML

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  
<svg id="svg-container" width="100%" height="100%"></svg>

CSS

svg {
      border: 1px solid #ccc;
      height:900px;
    }

JavaScript

function createCircle(x, y, radius, color) {
      const circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
      circle.setAttribute("cx", x);
      circle.setAttribute("cy", y);
      circle.setAttribute("r", radius);
      circle.setAttribute("fill", color);
      return circle;
    }

    function getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    function getRandomRadius(min, max) {
      return Math.random() * (max - min) + min;
    }

    function getRandomSpeed() {
      return (Math.random() - 0.5) * 2;
    }

    function createLine(x1, y1, x2, y2) {
      const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
      line.setAttribute("x1", x1);
      line.setAttribute("y1", y1);
      line.setAttribute("x2", x2);
      line.setAttribute("y2", y2);
      line.setAttribute("stroke", "black");
      return line;
    }

    function calculateDistance(x1, y1, x2, y2) {
      return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
    }

    function animateCircles() {
      const svgContainer = document.getElementById("svg-container");

      const circles = [];
      const lines = [];
      const numCircles = 50;
      const connectDistance = 150; // Maximum distance to draw a line between circles

      for (let i = 0; i < numCircles; i++) {
        const x = Math.random() * (window.innerWidth - 40) + 20;
        const y = Math.random() * (window.innerHeight - 40) + 20;
        const radius = getRandomRadius(10, 30);
        const color = getRandomColor();
        const dx = getRandomSpeed();
        const dy = getRandomSpeed();

        const circle = createCircle(x, y, radius, color);
        svgContainer.appendChild(circle);
        circles.push({ element: circle, dx, dy });
      }

      function moveCircles() {
        circles.forEach((circle,...