JSFiddle - React, Tailwind, and code Playground

by lchau

CSS

text {
  font-size: 24px;
}

.pentagon {
  fill: #f0f0f0;
  stroke: silver;
  stroke-width: 2px;
  shape-rendering: optimizeEdges;
}

JavaScript

var width = 350,
  height = 350,
  margin = {
    top: 50,
    right: 50,
    bottom: 50,
    left: 50
  };

function createPolygon(sides) {
  return Array.apply(null, new Array(sides))
    .map(function(element, index) {
      var theta = 2 * Math.PI * (index / sides);
      var x = -Math.cos(theta);
      var y = Math.sin(theta);
      return {
        x: x,
        y: y
      };
    });
}

function createScale(data, range, getter) {
  return d3.scale.linear()
    .domain(d3.extent(data, getter))
    .range([0, range]);
}

var data = createPolygon(5);
var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", 
        "translate(" + margin.top + "," + margin.left + ") " +
        "scale(0.5)");

var scaleX = createScale(data, width, function(datum) {
  return datum.x;
});

var scaleY = scaleX;

var polygon = svg.selectAll("polygon")
  .data([data])
  .enter()
  .append("polygon")
  .attr("points", function(d) {
    return d.map(function(d) {
      return [scaleX(d.x), scaleY(d.y)].join(",");
    }).join(" ");
  })
  .attr("class", "pentagon");

svg.selectAll("text")
  .data(data)
  .enter()
  .append("text")
  .text(function(datum) {
    var x = Math.round(scaleX(datum.x));
    var y = Math.round(scaleY(datum.y));
    return "(" + x + ", " + y + ")";
  })
  .attr({
    x: function(datum) {
      return scaleX(datum.x) + 20;
    },
    y: function(datum) {
      return scaleY(datum.y);
    }
  })
  .style("fill", "red")
  .style("text-anchor", "start");

var points = data.map(function(item) { return [item.x, item.y]});
var centroid = d3.geom.polygon(points).centroid();
svg
.append("g")
//.attr("translate", "transform(" + centroid[0] + ", " + centroid[1] + ")
.append("text")
  .text(function() {
      return "center"
  });

console.log(centroid)