为什么可以't我得到了这个d3.js文本的边界框

Why can't I get the Bounding Box of this d3.js text?

本文关键字:d3 js 文本 边界 为什么      更新时间:2024-05-06

我有以下代码,它使用d3.js成功地将文本绘制到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.getBBox());

但它给了我一个错误:

Uncaught TypeError: myRect.getBBox is not a function

myRect是一个d3选择,而不是html元素。

试试这个代码:

myRect.node().getBBox();

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());
svg{
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="500" height="800"></svg>