JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<center>
<div class="centered">
Number of side of the polygon.
<script src="https://d3js.org/d3.v5.js"></script>
<p>
<input id="ranger" type="range" min="3" max="32" value="5">
<label for="ranger"></label>
</p>
</div>
</center>
</body>
CSS
/* body {
width: 100%;
Firefox
display: -moz-box;
-moz-box-pack: center;
-moz-box-align: center;
Safari and Chrome
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
W3C
display: box;
box-pack: center;
box-align: center;
} */
/*
svg {
display: block;
margin-left: auto;
margin-right: auto;
}
*/
svg {
display: block;
margin: auto;
width: 300px;
height: 300px;
}
JavaScript
// Just setup, not related to problem.
const svg = d3.select("body")
.append("svg")
.attr("width", 500)
.attr("height", 500);
const circle = svg.append("circle")
.attr("cx", "150")
.attr("cy", "150")
.attr("r", "100")
.attr("fill", "none")
.attr("stroke", "black");
const polygon = svg.append("polygon")
.attr("fill", "none")
.attr("stroke", "blue");
const circleElement = circle.node();
const ranger = d3.select("#ranger").on("input", update);
const label = d3.select("label");
// This function contains all the relevant logic.
function update() {
let count = ranger.node().value;
label.text(count);
// Calculate step length as circumference / number of points.
const step = circleElement.getTotalLength() / count;
// Build an array of all points on the circle.
const data = Array.from({length: count}, (_, i) => {
const point = circleElement.getPointAtLength(i * step); // Get coordinates of next point.
return `${point.x},${point.y}`;
});
polygon.attr("points", data.join(" "));
}
update();