我正在引用这个例子来制作我的可折叠树:
http://bl.ocks.org/mbostock/4339083
目前我的主要目标是用矩形替换圆圈,然后用我想要的文本填充矩形。
经过一些研究,我意识到我应该使用 getBBox这样矩形的尺寸将与文本的尺寸相匹配。但是,我相信我放在每个矩形中的文本的长度可能会有所不同,因此会使树中的每个矩形大小不同......理想情况下,我想让每个矩形的大小相同,以便树看起来一致。有没有办法做到这一点?谢谢!
相关代码:
var node = svg.selectAll("g.node")
.data(nodes, function(d) { return d.id || (d.id = ++i); });
// Enter any new nodes at the parent's previous position.
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; })
.on("click", click);
//where text is being appended... will need to use getBBox when appending rect
var text = nodeEnter.append("text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { return d.name; });
//var bbox = text.node().getBBox();
nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH)
.attr("stroke", "black")
.attr("stroke-width", 1)
.style("fill", function(d) { return d._children ? "lightsteelblue" : "#FFF"; });
网站上提供了所有代码,但如果需要更多信息,我愿意提供。 datatest.json
是我为感兴趣的人制作的:
{
"name": "Group 1",
"children": [
{
"name": "Sub Group 1",
"children": [
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
},
{
"name": "D"
},
{
"name": "E"
},
{
"name": "F"
},
{
"name": "G"
},
{
"name": "H"
}
]
},
{
"name": "Sub Group 2",
"children": [
{
"name": "I"
},
{
"name": "J"
},
{
"name": "K"
},
{
"name": "L"
},
{
"name": "M"
},
{
"name": "N"
},
{
"name": "O"
},
{
"name": "P"
},
{
"name": "Q"
}
]
},
{
"name": "Person 1"
},
{
"name": "Person 2"
}
]
}
最佳答案
您可以在插入矩形之前计算最大边界框文本宽度:
// Insert the text elements ...
// Compute the maximum bounding box width
var maxTextWidth = d3.max(text, function() {
return d3.select(this).node().getBBox();
});
// Insert the rect before the text element
nodeEnter.insert('rect', 'text')
.attr("width", maxTextWidth)
.attr("height", rectH);
此外,这样文本将覆盖在矩形上。
关于javascript - D3 树布局 : How to fill rectangles with text, 但它们的大小统一吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17349467/