Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 672
Saqib Ali Avatar asked Apr 11 '16 04:04

Saqib Ali


People also ask

How to get the underlying DOM node of a D3 selection?

d3 has a function ".node ()" which returns the the underlying DOM node of the first item in the d3 selection: Show activity on this post. You can call "getBBox ()" on SVG elements to get their bounding box in terms of SVG coordinates.

How to get the bounding box of an SVG element?

You can call "getBBox ()" on SVG elements to get their bounding box in terms of SVG coordinates.

What does the Boolean value mean in the bounding box?

A boolean value indicating that the stroke should be included in the bounding box, defaults to false . A boolean value indicating that the markers should be included in the bounding box, defaults to false . A boolean value indicating that the bounding box should be clipped, defaults to false .

What is the return value of the bounding box?

The returned value is a SVGRect object, which defines the bounding box. This value is irrespective of any transformation attribute applied to it or the parent elements. Found a problem with this page?


1 Answers

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>
like image 66
Gilsha Avatar answered Oct 30 '22 21:10

Gilsha