9

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
JackHasaKeyboard
  • 1,599
  • 1
  • 16
  • 29
Saqib Ali
  • 11,931
  • 41
  • 133
  • 272
  • 5
    `myRect` is a D3 object, not a `SVGRectElement`. [`myRect[0][0]` should be.](http://stackoverflow.com/questions/10337640/how-to-access-the-dom-element-that-correlates-to-a-d3-svg-object) – Amadan Apr 11 '16 at 04:59
  • 2
    For non-d3 people - `getBBox` is a SVG function, not a generic HTML function => you must create text element with SVG namespace using `createElementNS` instead of basic `createElement` example: `document.createElementNS('http://www.w3.org/2000/svg', 'text')` – jave.web Oct 03 '19 at 19:11
  • @jave-web 's comment about the svg namespace [also applies to d3 people using `d3.create`](https://github.com/d3/d3-selection/blob/v3.0.0/README.md#create). – djvg Feb 02 '23 at 16:10

1 Answers1

21

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>
Gilsha
  • 14,431
  • 3
  • 32
  • 47
  • If the selection is created using `d3.create()`, don't forget to add the svg namespace explicitly, as in `d3.create('svg:text')`, otherwise you'll still get the same error. See [docs](https://github.com/d3/d3-selection/blob/v3.0.0/README.md#create). – djvg Feb 02 '23 at 16:05