Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting text width in SVG prior to rendering

Tags:

text

width

svg

size

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.

like image 367
radlan Avatar asked Oct 08 '13 13:10

radlan


People also ask

How do I get SVG text width?

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.

How do I center text in SVG?

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).


1 Answers

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()

like image 185
matanster Avatar answered Sep 29 '22 10:09

matanster