为什么我不能得到这个d3.js文本的边界框?

Saq*_*Ali 3 javascript svg d3.js

我有以下代码使用d3.js成功地将我的文本绘制到SVG上:

var myRect = svgContainer.append("text")
    .attr("x", 10)
    .attr("y", 20)
    .text("Lorem Ipsum")
    .attr("font-weight", "bold")
    .attr("fill", "white");
Run Code Online (Sandbox Code Playgroud)

现在我想获得该文本的边界框.我该怎么做??我尝试了以下方法:

console.log("getBBox = ", myRect.getBBox());
Run Code Online (Sandbox Code Playgroud)

但它给了我这个错误:

Uncaught TypeError: myRect.getBBox is not a function
Run Code Online (Sandbox Code Playgroud)

Gil*_*sha 12

myRect是d3选择而不是html元素.

试试这段代码:

myRect.node().getBBox();
Run Code Online (Sandbox Code Playgroud)

var svgContainer = d3.select("svg");  

var myRect = svgContainer.append("text")
                .attr("x", 10)
                .attr("y", 20)
                .text("Lorem Ipsum")
                .attr("font-weight", "bold")
                .attr("fill", "white");

console.log("getBBox = ", myRect.node().getBBox());
Run Code Online (Sandbox Code Playgroud)
svg{
  background: green;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="800"></svg>
Run Code Online (Sandbox Code Playgroud)