我正在尝试绘制一个矩形形状,我可以在d3树形图中拟合一些数据。但我不知道如何才能做到这一点。我在这里有初始的plunkr:http://plnkr.co/edit/AoqY1xoRlwyK3VAxYuhz?p=preview 以下是我知道我可以做的附加文字:
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; })
.style("fill-opacity", 1e-6);
任何人都可以在这里帮助我,或者指出一些我可以参考的文件。
答案 0 :(得分:2)
您已在此处拥有组元素。话虽这么说,你只需要附加你的矩形(不要在这里注意魔法数字,你可以在以后改变它们):
var nodeRect = nodeEnter.append("rect")
.attr("height", 14)
.style("fill", "dodgerblue")
.attr("rx", 4)
.attr("ry", 4)
.attr("y", -7);
然后,在创建/附加文本选择之后,计算文本的长度。我在这里使用this.nextSibling.nextSibling
,因为我知道文本与矩形的关系:
nodeRect.attr("width", function(d) {
return this.nextSibling.nextSibling.getComputedTextLength() + 30
})
.attr("x", function(d, i) {
return d._children || d.depth === 0 ? -(this.nextSibling.nextSibling.getComputedTextLength() + 14) : -14
});
以下是您更新的Plunker:http://plnkr.co/edit/a32rYZT6cSZ0c5zQrC6W?p=preview