Saqib Ali
Saqib Ali

Reputation: 12575

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

I have the the following code that successfully draws my text onto an SVG using d3.js:

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

Now I want to get the bounding box of that text. How do I do it?? I tried the following:

console.log("getBBox = ", myRect.getBBox());

But it gave me this error:

Uncaught TypeError: myRect.getBBox is not a function

Upvotes: 9

Views: 12522

Answers (1)

Gilsha
Gilsha

Reputation: 14591

myRect is a d3 selection and not an html element.

Try this code:

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>

Upvotes: 21

Related Questions