我工作的一些的ECMAScript/JavaScript来SVG文件,并需要获得width和height一个的text元素,所以我可以调整,围绕它的矩形.在HTML中,我可以使用元素上的offsetWidth和offsetHeight属性,但看起来这些属性不可用.
这是我需要使用的片段.每当我更改文本时我都需要更改矩形的宽度,但我不知道如何获得元素的实际width(以像素为单位)text.
<rect x="100" y="100" width="100" height="100" />
<text>Some Text</text>
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
我想显示一个rect与text它旁边的标签.的宽度rect应该伸展到SVG容器的宽度时,该文本的少的宽度,这是动态的,并且可以是任何可变的长度.
var text = 'Foobar';
var textWidth = 50; //how to calculate this?
var plotWidth = 400;
var barWidth = plotWidth-textWidth;
var plot = d3.select(container)
.insert("svg")
.attr('width', plotWidth)
.attr('height', 50);
plot.append("rect")
.style("fill", "steelblue")
.attr("x", 0)
.attr("width", barWidth)
.attr("y", 0)
.attr("height", 50);
plot.append("text")
.attr("x", barWidth)
.attr("y", 28)
.text(text);
Run Code Online (Sandbox Code Playgroud)
在绘制之前,如何使用D3计算文本的宽度?或者我如何定位和大小取决于可变长度文本的维度的元素?