Skip to content

Instantly share code, notes, and snippets.

@takehiko
Created March 21, 2014 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takehiko/9685965 to your computer and use it in GitHub Desktop.
Save takehiko/9685965 to your computer and use it in GitHub Desktop.
Regular Polygons
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>Regular Polygons</title>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
function gen_poly(n) {
var poly = [];
var t1 = 2 * Math.PI / n;
var t2 = Math.PI / n;
for (var i = 0; i < n; i++) {
var t = t2 + t1 * i;
var x = Math.sin(t);
var y = Math.cos(t);
poly.push([x, y]);
}
return poly;
}
var line = d3.svg.line()
.x(function(d) { return d[0]; })
.y(function(d) { return d[1]; })
.interpolate("interpolate");
var side = 100;
var width = 400;
var height = 400;
var opt_fill = true;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("fill", opt_fill ? "#ffffe0" : "none")
.attr("stroke", "none");
for (i = 12; i >= 3; i--) {
// var t1 = 2 * Math.PI / i;
var t2 = Math.PI / i;
var r = 0.5 / Math.sin(t2);
var side_r = side * r;
var trans = "translate(" + (width / 2) + "," + (height / 2) + ") scale(" + side_r + "," + side_r + ")";
var g = svg.append("g")
.attr("transform", trans);
g.selectAll("path" + i)
.data([gen_poly(i)])
.enter()
.append("path")
.attr("d", function(d) { return line(d) + "z"; })
.attr("fill", opt_fill ? "#ccf" : "none")
.attr("stroke", "black")
.attr("stroke-width", 2 / side_r);
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment