如何定位具有可变尺寸的 d3 树形图的节点?
这是我目前所拥有的,正如你所看到的那样,定位有偏差
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
元素上设置了 x
和 y
,但没有在相应的 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 .
关于javascript - d3树节点位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28742899/