JSFiddle - React, Tailwind, and code Playground

by abigel87

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>D3 Circle Gradient</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
 <svg width="500" height="500"></svg>
 </body>
</html>

JavaScript

const renderCircle = () => {

  const svg = d3.select("svg");
  svg.selectAll("*").remove();

  const margin = {
    top: 50,
    right: 50,
    bottom: 50,
    left: 50
  };

  const width = 500;
  const height = 500;
  const g = svg.append("g").attr("transform", `translate(${margin.left},${margin.top})`);

  // Circle properties
  const cx = width / 2;
  const cy = height / 2;
  const radius = 0;
  const finalRadius = Math.min(width, height) / 4;
  const strokeWidth = 10;


  const gradientId = "linearGrad";
  const gradient = svg.append("defs")
    .append("linearGradient")
    .attr("id", gradientId)
    .attr("gradientUnits", "objectBoundingBox");


  gradient.append("stop")
    .attr("offset", "0%")
    .attr("stop-color", "red");

  gradient.append("stop")
    .attr("offset", "100%")
    .attr("stop-color", "gray");

  const circle = g.append("circle")
    .attr("cx", cx)
    .attr("cy", cy)
    .attr("r", radius)
    .attr("fill", "none")
    .attr("stroke", `url(#${gradientId})`)
    .attr("stroke-width", strokeWidth)
    .transition()
    .duration(0)
    .attr("r", finalRadius)
    .on("end", function() {


      let angle = 0;
      let step = 1;

      d3.interval(() => {
        angle += step;
        if (angle <= 360) {
          gradient
            .attr("x1", `50%`)
            .attr("y1", `50%`)

            .attr("x2", `${50 + Math.round((Math.sin(angle * Math.PI / 180) * finalRadius)/(2*finalRadius / 100))}%`)
            .attr("y2", `${Math.round((finalRadius - Math.cos(angle * Math.PI / 180)*finalRadius)/(2 * finalRadius / 100))}%`);
        };
      }, 10);
    });

};

renderCircle();