Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active March 4, 2019 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mbostock/2932721 to your computer and use it in GitHub Desktop.
Save mbostock/2932721 to your computer and use it in GitHub Desktop.
Squares ↔ Hexagons
license: gpl-3.0
redirect: https://observablehq.com/@mbostock/regular-plane-tilings/2

These aren’t regular hexagons; they’re too tall.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
path {
fill: none;
stroke: #000;
stroke-width: .6px;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 960,
height = 500,
size = 50,
offset = 0;
var voronoi = d3.geom.voronoi()
.clipExtent([[-1, -1], [width + 1, height + 1]]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.selectAll("g")
.data(voronoi(vertices()))
.enter().append("g");
var path = g.append("path")
.attr("d", function(d) { return "M" + d.join("L") + "Z"; });
var circle = g.append("circle")
.attr("transform", function(d) { return "translate(" + d + ")"; })
.attr("r", 2);
d3.timer(function() {
++offset; if (offset > size) offset -= size;
var data = vertices();
path.data(voronoi(data)).attr("d", function(d) { return "M" + d.join("L") + "Z"; });
circle.data(vertices).attr("transform", function(d) { return "translate(" + d + ")"; });
});
function vertices() {
return d3.merge(d3.range(-size, width + size, size).map(function(x, i) {
return d3.range(-size, height + size, size).map(function(y, j) {
return [x + (j & 1 ? -offset : offset), y];
});
}));
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment