Svg.js: Text width without rendering

Created on 26 Jul 2019  路  9Comments  路  Source: svgdotjs/svg.js

Hello,
I use the following code to get the width of an text element:
const textElement = group.text("Hello my name is Leon").textElement.bbox().width
but it is possible to get this width without the render of this text?, because i want to have a rectangle of multiple text elements and i want to calculate the max width.

Thanks, Leon :)

All 9 comments

No unfortunately that's not possible :/

@leonschwanitz You can use something like text-to-svg for this kind of calculation without rendering.

TextToSVG.getMetrics('my text here', option = {})
returns...
{ "x": 0, "y": -63.3515625, "baseline": 0, "width": 180, "height": 72, "ascender": 63.3515625, "descender": -8.6484375 }

@notchris Thank you! :)

This is closed? Is a feature like this not planned? It is defiantly something I would like in the library. Aka I found this issue by googling how to do this.

@Linkviii The main issue is that if you wanted calculate the bounding box using the general methods, the text would need to be available to the dom beforehand. I agree it that it would be a cool feature, but the implementation would likely require you to render the text to canvas (which has text metrics calculations) first, before rendering, and that's out of scope of the lib.

Exactly. You either need the font file, calculate the bounding box of every character in the text, take letter spacing and sizing into account and sum it up to get the text box without rendering or you just render it somewhere and let the browser figure it out.

You can see that the first method is not fun to use especially because you need to supply the font file

I had been using a canvas object to get text width and noticed the the results did not match the svg bbox.

It's not necessarily the same. I think canvas gives you more metrics and their bounding box could be the tightest box around all charackters while the bounding box in svg takes into account the tallest charackter you have in the whole font

Was this page helpful?
0 / 5 - 0 ratings

Related issues

wout picture wout  路  4Comments

liho98 picture liho98  路  8Comments

mroloux picture mroloux  路  8Comments

Fuzzyma picture Fuzzyma  路  6Comments

Mourdraug picture Mourdraug  路  5Comments