Skip to content

Instantly share code, notes, and snippets.

@fabiovalse
Last active January 20, 2024 19:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiovalse/8543484 to your computer and use it in GitHub Desktop.
Save fabiovalse/8543484 to your computer and use it in GitHub Desktop.
Regular Polygon Vertices Generator

This script allows to generate the vertices, of a regular polygon, as svg circles. It is possible to specify:

  • the number of polygon sides;
  • the radius of the polygon;
  • the svg width and height.

The vertices coordinates are generated splitting a circumference in N parts, corresponding to the polygon sides. If N=1 then the vertice coordinates correspond to the center of the circumference.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Regular Polygon Vertices GENERATOR</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="index.js"></script>
</head>
<body onload="main()"></body>
</html>
(function() {
var width = 962; // svg width
var height = 502; // svg height
var sides = 5; // polygon vertices number
var radius = width/4 - 50; // polygon radius
window.main = function() {
svg = d3.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.attr('viewBox', [-width/2, -height/2, width, height].join(' '));
container = svg.append('g');
crd = polygon(0, 0, radius, sides);
for (var i = 0; i < crd.length; i++) {
container.append('circle')
.attr('r', 10)
.attr('cx', crd[i][0])
.attr('cy', crd[i][1])
.attr('fill', '#FCE29D')
.attr('stroke', '#F7B127')
.attr('stroke-width', 4);
}
}
/* GIVEN x and y (the center coordinates), the radius and the number of polygon sides RETURNS AN ARRAY OF VERTICE COORDINATES */
function polygon(x, y, radius, sides) {
var crd = [];
/* 1 SIDE CASE */
if (sides == 1)
return [[x, y]];
/* > 1 SIDE CASEs */
for (var i = 0; i < sides; i++) {
crd.push([(x + (Math.sin(2 * Math.PI * i / sides) * radius)), (y - (Math.cos(2 * Math.PI * i / sides) * radius))]);
}
return crd;
}
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment