d3-regular-polygon v0.0.4
d3-regular-polygon
This is a module for building regular polygons with a variable number of edges
in d3
. It is built to work with SVG path
tags
and canvas
.
Installing
If you use NPM, npm install d3-polygon
. Otherwise, download the latest release.
API Reference
# d3.regularPolygon(cx = 0, cy = 0, r, edges, rotation = 0)
Constructs a new default constructor for regular polygons. You can optionally set the center x position cx
, the center y position cy
, the radius r
, the number of sides edges
, or the rotation of the first vertex (in radians) rotation
.
Starting with
var poly = d3.regularPolygon()
you can also set those paramters using one of the following method-chaining constructor methods:
Constructor Methods
# poly.radius(r)
Sets the radius of the polygon.
# poly.center(x, y)
Sets the center of the polygon. If there is only one argument, it sets x = x0, y = x1.
# poly.edges(numEdges)
Sets the number of sides the polygon has. Should be an integer greater or equal to 3.
#poly.rotation(rotation)
Sets the amount of (in radians) you want the polygon to rotate (relative to the position of the first vertex).
Vertex methods
You can also get information about the vertices of your regular polygon. These methods are designed to make it easy to render the polygon in different contexts.
# poly.coords()
Returns the coordinates as an array of 2-item arrays [x0, y0, x1,y1], etc.
# poly.path()
Returns the SVG path of the polygon (i.e. the d-attribute).
In other words, rendering the polygon is as easy as:
d3.select("#my-graphic")
.append("path")
.attr("d", poly.path());
# poly.polygon()
Returns the SVG <polygon>
points attribute for the polygon.
In other words, you can also render a polygon as:
selection.append("polygon")
.attr("points", poly.polygon());
# poly.canvas(context)
This renders the polygon to canvas. Here's an example of how to use that:
var canvas = document.getElementById("my-canvas");
var context = canvas.getContext("2d");
context.fillStyle = "maroon";
poly.canvas(context);
context.fill();
Measurements
Finally, you can run measurements of the polygon. This can be useful if you want to dynamically size based on the value of certain elements (for instance, size elements based on the area or the perimeter of the polygon).
# poly.apothem()
This returns the size of theapothem, or the distance from the center of the polygon to the midpoint between any two vertices.
# poly.sideLength()
Shows the length of any given side.
# poly.perimeter()
Shows the perimeter of the polygon.
# poly.area()
Shows the area of the polygon.