I'm currently trying to create a hex grid using d3.js and the hexbin plugin for d3.js. The problem I'm having is that I always have empty hexagons or entire empty rows in my grid instead of all hexagons nice together.
Any ideas how to fix this?
My code:
var margin = {
top: 80,
right: 20,
bottom: 50,
left: 80
},
width = $(window).width() - margin.left - margin.right,
height = $(window).height() - 28 - margin.top - margin.bottom;
var points = [];
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 12; j++) {
points.push([Math.floor(width * j / 12), Math.floor(height * i / 8)]);
}
}
var hexbin = d3.hexbin()
.size([width, height])
.radius((width / 12) / 2);
var svg = d3.select($("#grid").get(0)).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("g")
.selectAll(".hexagon")
.data(hexbin(points))
.enter().append("path")
.attr("class", "hexagon")
.attr("d", function (d) {
return hexbin.hexagon();
})
.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
})
.attr("stroke", "#fff")
.attr("stroke-width", "2px")
.style("fill", function (d) {
return "#dcdcdc"; //color(d.length);
});
Change your points data so that, when hexagons are added, the translation is not pushing them one hexagon too far right or one row too far down:
Something like this:
var points = [];
for (var i = 0; i < 8; i++) {
for (var j = 0; j < 12; j++) {
points.push([Math.floor(width * j / 14), Math.floor(height * i / 11)]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With