I want to put a rectangle around a text in SVG.
The height of the text is known to me (the font-size
attribute of the text
element). But the width is dependent on the actual content. Using getBBox()
or getComputedTextLength()
should work. But this only works after rendering.
Is there a way to specify that in an other way? For example defining the x
and width
attributes relative to other values? I didn't find anything like that in the SVG Spec.
To get the SVG's text element's width and height with JavaScript, we can call the getBBox method of the text element to get the text's width and height. We get the text element with document. querySelector . Then we call getBBox on the returned textElement to get an object with the dimensions of the text.
Set the position of the text to the absolute center of the element in which you want to center it: If it's the parent, you could just do x="50%" y ="50%" . If it's another element, x would be the x of that element + half its width (and similar for y but with the height).
Figuring where text ends presumably requires roughly the same underlying code path as the rendering itself implements - going through the width of each character based on the font and style, etc... As I am not aware the SVG standards define a method for directly getting this information without doing the actual full rendering, till such methods emerge or are reported here by others, the approach should be to render invisibly before doing the actual rendering.
You can do that in a hidden layer (z-index, opacity and stuff) or outside the visible viewport, whichever works best in experimentation. You just need to get the browser do the rendering to find out, so you render invisibly for that sake, then use getComputedTextLength()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With