Javascript's getBBox() provides a box that is taller than its content text. Why?

Viewed 5221

I'm using D3.js to draw some text ("100%") on an SVG Container.

Now I'm trying to figure out the dimensions of the bounding box around that text.

This is how I do it:

      var label = svgContainer.append("text")
        .attr("x", 200)
        .attr("y", 200)
        .text("100%")
        .attr("font-family", "Courier New")
        .attr("font-weight", "bold")
        .attr("font-size", "10px")
        .attr("fill", "black");
        .attr("transform", function(d){
            var bb = this.getBBox();
            console.log("bb.width = ", bb.width);
            console.log("bb.height = ", bb.height);
            return "translate(0, 0)";
          }
        );

Not only does this draw the string "100%" on my screen, but in the console.log, it also outputs the width and height of the bounding box (24 & 11.5 respectively!);

Now I want to visualize the aforementioned bounding box on the screen. So before the code above, I prepend the following code:

        var rect = svgContainer.append("rect")
          .attr("x", 200)
          .attr("y", 200-11.5)
          .attr("width", 24)
          .attr("height", 11.5)
          .attr("fill", "pink");

When I run this altered code, I expect to see a pink bounding box around the "100%" string. But I see the following instead!

enter image description here

Why is the pink bounding box taller than the text? I need to get the dimensions of the actual bounding-box of the text -- not something taller than it. How do I do that?

Here is the Plunker: https://plnkr.co/edit/XoVSZwTBNXhdKKJKkYWn

2 Answers
Related