D3.js将rect调整为文本大小:getBBox()? [英] D3.js adjust rect to text size: getBBox()?
问题描述
我正在使用D3.js创建力导向图,请参见JSFiddle: http://jsfiddle.net/pwxecn8q/.
I'm creating a force directed graph using D3.js, see JSFiddle: http://jsfiddle.net/pwxecn8q/.
text
和rect
放在同一组中.追加rect
时,我想为同一组选择text
元素.在其上调用getBBox()
并使用这些值来调整rect
的大小以适合其中的文本.但是,我不确定在添加rect
s ...
The text
and rect
are placed in the same group. When appending the rect
s I want to select the text
element for the same group. Call getBBox()
on it and use those values to resize the rect
to fit the text "in" it. However, I'm unsure how to select the text
element from the same group when appending the rect
s...
关于如何解决此问题的任何建议?
Any suggestion on how to go about this?
相关代码:
var color = d3.scale.category20();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var force = d3.layout.force()
.gravity(.05)
.distance(100)
.charge(-100)
.size([width, height]);
force.nodes(graphData.nodes)
.links(graphData.links)
.start();
var link = svg.selectAll(".link")
.data(graphData.links)
.enter().append("line")
.attr("class", "link");
var node = svg.selectAll("g.node")
.data(graphData.nodes)
.enter()
.append("g")
.attr("class", "node")
node.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", 10)
.attr("height", 10)
.style("fill", function (d) {
return color(d.group);
})
.call(force.drag);
node.append("text")
.attr("x", 0)
.attr("y", 10)
.attr("text-anchor", "middle")
.text(function (d) {
return d.name
})
force.on("tick", function () {
link.attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
推荐答案
您可以使用节点的边界框(g
元素,其中包含文本).
You can use the Bounding Box of the node (g
element, which contains the text).
node.selectAll('rect')
.attr("width", function(d) {return this.parentNode.getBBox().width;})
更新的jsfiddle: http://jsfiddle.net/pwxecn8q/3/
Updated jsfiddle: http://jsfiddle.net/pwxecn8q/3/
这篇关于D3.js将rect调整为文本大小:getBBox()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!