Reputation: 759
I'm creating a force directed graph using D3.js, see JSFiddle: http://jsfiddle.net/pwxecn8q/.
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?
The relevant code:
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 + ")";
});
});
Upvotes: 0
Views: 8352
Reputation: 7403
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;})
Updated jsfiddle: http://jsfiddle.net/pwxecn8q/3/
Upvotes: 10