I know this has been asked here before but I'm encountering a very weird issue...
I'm trying to give arbitrarily sized text a coloured background. What I'm doing is: creating the text, calculating the coordinates and dimensions of the text, and then creating a rectangle with the same dimensions and coordinates, ensuring it's inserted before the text so it does not cover it up. I'm using d3 for all of this.
The issue is that sometimes the rectangle is slightly too thin, so some text sticks out the end (words ending in "s" seem to be the main offender, weirdly). The vertical placement of the rectangles are also slightly too high, so there's some blank space at the top, and any "dangling" letters like g, p, etc. extend beneath the rectangle.
See the following image:
Here's the code I'm using:
let textContainer = self.svg.append("g")
.attr("id", "textContainer");
textContainer.append("text")
.attr("x", xcoordinate)
.attr("y", ycoordinate)
.attr("text-anchor", "middle")
.text(text);
let bBox = (textContainer.node() as any).getBBox();
textContainer.insert("rect", "#textContainer text")
.attr("width", bBox.width)
.attr("height", bBox.height)
.attr("x", bBox.x)
.attr("y", bBox.y)
.attr("fill", "gray");
Why is this issue happening?