d3树节点位置

d3 tree node position

如何定位具有可变尺寸的 d3 树形图的节点?[​​=12=]

这是我目前所掌握的,如您所见,定位有偏差

http://jsfiddle.net/cdad0jyz/1/

我试过使用分离法:

var tree = d3.layout.tree()
        .nodeSize([10,10])
         .separation(function(a, b) {
               var width = 200, // here should be a value calculated for each node
                   distance = width / 2 + 16; 
                   return distance;
           });

在您的代码中,您在 text 元素上设置了 xy,但没有在相应的 rects 上设置。更复杂的是,每个矩形都有随机的宽度和高度,这使得它很难在文本上居中。

这是解决问题的一种方法:

nodeEnter.append("rect")
    .attr("width",  genRand)  //rectW
    .attr("height", genRand) // rectH
    .attr("x", function(){
        return (rectW / 2) - (d3.select(this).attr('width') / 2);
    })
    .attr("y", function(){
        return (rectH / 2) - (d3.select(this).attr('height') / 2);
    })
    .attr("stroke", "black")
    .attr("stroke-width", 1)
    .style("fill", function (d) {
    return d._children ? "lightsteelblue" : "#fff";
});

已更新 fiddle