Search code examples
javascriptsvg2dbounding-boxsvg.js

Calculate bounding box coordinates from the coordinates of an SVG text object


I'm currently trying to figure out how SVG.js calculates the corrected bounding box x, y coordinates (top left corner) from an SVG text object.

My SVG object looks like the following:

<svg  xmlns="http://www.w3.org/2000/svg" width="266" height="59" viewBox="0 0 266 59">
  <text id="TText" data-name="TText" fill="#707070" font-size="50" font-family="Boogaloo"><tspan x="0" y="0">TText</tspan></text>
</svg>

If I add this code into SVG.js then the position is y-offset by 11 pixels (which I assume is the position when taking into consideration that SVG is based on the baseline). Can someone explain how the bounding box x and y coordinates are calculated. I tried to solve it by digging through the SVG.js repo, but couldn't solve it myself.

I would assume this is based on the font? If that's the case how does one extract that information out of a font file?

Here's my SVG.js code, that shows the corrected X, Y bounding box coordinates.

var draw = SVG().addTo('body');
var text = draw.text('TText');
text.font({
  family: 'Boogaloo',
  size: 50,
});
console.log(text.bbox());

Solution

  • The simple answer is: we use the browser api to get the bounding box (el.getBBox()). Our bbox() method is just a simple wrapper around that. In case of text we don't calculate any corrected bounding box. We have some magic involved when moving the text because text is normally moved by its baseline but we unified the api so that all shapes are moved by their upper left corner.

    If you want to know how a browser calculates the bounding box of text, you can have a look at this answer: reproduce Bounding Box of text in Browsers

    TL:DR the numbers you get are different from browser to browser. And ofc you need the font file