在 SVG 图形中,我创建了由矩形和一些文本组成的节点元素。文本的数量可能会有很大差异,因此我想根据文本的宽度设置矩形的宽度。
下面是使用 D3.js 创建的矩形(使用固定的宽度和高度值):
var rects = nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH);
后跟文本元素:
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;
});
如您所见,目前我将文本置于可用空间的中心。然后我尝试根据它们的文本设置矩形的宽度,但我从来没有同时获得矩形元素和文本 HTML 元素(对于 getBBox())。这是我的尝试之一:
rects.attr("width",
d => this.getBBox().width + 20
);
但显然 this
是错误的,因为它指的是 rects
而不是文本。
这里正确的做法是什么?
最佳答案
我会使用 getComputedTextLength
测量文本。我不知道 D3.js 中是否有等效项我的回答是使用纯 javascript 并假设矩形和文本中心是 {x:50,y:25 } 并且您使用的是 text{dominant-baseline:middle;text-anchor:middle;}
let text_length = txt.getComputedTextLength();
rct.setAttributeNS(null,"width",text_length )
rct.setAttributeNS(null,"x",(50 - text_length/2) )
svg{border:1px solid}
text{dominant-baseline:middle;text-anchor:middle;}
<svg viewBox="0 0 100 50">
<rect x="25" y="12.5" width="50" height="25" stroke="black" fill="none" id="rct" />
<text x="50" y="25" id="txt">Test text</text>
</svg>
或者代替 txt.getComputedTextLength()
你可以使用 txt.textLength.baseVal.value
关于javascript - 如何根据文本宽度动态调整 SVG 矩形的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53814886/