六角网格与d3.js

时间:2013-01-30 09:38:08

标签: javascript d3.js

我目前正在尝试使用d3.jshexbin plugin d3.js创建一个十六进制网格。我遇到的问题是我的网格中总是有空六边形或整个空行而不是所有六边形都很好。

任何想法如何解决这个问题?

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); 
});

1 个答案:

答案 0 :(得分:8)

更改您的点数据,以便在添加六边形时,平移不会将一个六边形向右推或向下推得太远:

这样的事情:

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)]);
    }
}