In an SVG graph I create node elements consisting of a rectangle and some text. The amount of text can differ significantly, hence I'd like to set the width of the rect based on the width of the text.
Here's the creation of the rectangles with D3.js (using fixed width and height values):
var rects = nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH);
followed by the text element:
var nodeText = nodeEnter.append("text")
.attr("class", "node-text")
.attr("y", rectH / 2)
.attr("dy", ".35em")
.text(function (d) {
return d.data.name;
});
nodeText // The bounding box is valid not before the node addition happened actually.
.attr("x", function (d) {
return (rectW - this.getBBox().width) / 2;
});
As you can see, currently I center the text in the available space. Then I tried to set the widths of the rects based on their text, but I never get both, the rect element and the text HTML element (for getBBox()) at the same time. Here's one of my attempts:
rects.attr("width",
d => this.getBBox().width + 20
);
but obviously this
is wrong as it refers to rects
not the text.
What's the correct approach here?