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 to create a circle element in the SVG
    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 to generate a random color
    function getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    // Function to generate a random radius
    function getRandomRadius(min, max) {
      return Math.random() * (max - min) + min;
    }

    // Function to generate a random speed
    function getRandomSpeed() {
      return (Math.random() - 0.5) * 2;
    }

    // Function to animate the circles
    function animateCircles() {
      const svgContainer = document.getElementById("svg-container");

      const circles = [];
      const numCircles = 50;

      // Create initial circles
      for (let i = 0; i < numCircles; i++) {
        const x = Math.random() * (window.innerWidth - 40) + 20; // Ensure initial position is within the screen
        const y = Math.random() * (window.innerHeight - 40) + 20; // Ensure initial position is within the screen
        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 });
      }

      // Animation loop
      function moveCircles() {
        circles.forEach(circle => {
          const { element, dx, dy } = circle;
          const x = parseFloat(element.getAttribute("cx"));
          const y = parseFloat(element.getAttribute("cy"));
          const...