0

How to align text in an text tag without using the text-anchor attribute? My problem is that using the text-anchor will change the way the x and the y attributes are interpreted, and I don't want that, because I've perfectly set up the position of such element groups:

<text>
<tspan x="206" y="142.2">hello</tspan>
<tspan x="206" dy="15">there, all good?</span>
</text>

and I don't want it to be changed hence re-code the entire svg setup just for text layout purposes. If I for example apply a text-anchor="middle" here, this centers the texts okay, but it changes the x (206) to be the center of the text. I use the x value in my svg to place my text element at a precise spot in my system, hence other interpretations of x coordinates 1) break the entire layout, and 2) even make the precise placement of text elements impossible, as the inserted text may be of variable length, hence it becomes impossible to predict the needed x coordinate of a text tag to place it at the spot you want. So I figured there must be a better way to reach what I want?

DevelJoe
  • 856
  • 1
  • 10
  • 24

1 Answers1

1

You can manually center SVG text by adjusting the dx of each text fragment, using as input, the width that's returned from calling getComputedTextLength() on each fragment.

Michael Mullany
  • 30,283
  • 6
  • 81
  • 105
  • ouf; what you mean is like getting the length on each fragment, then get the biggest length, and center the others by applying either negative or positive dx values, according to 0.5 * the obtained differences? That's what you mean? And generally speaking, do you think that SVGs are suitable for drwaing x-y graphs with text labels at a given spot in a given orientation + alignment? Does not seem to be the case, I wonder if there's sth better suited than SVG.. – DevelJoe Mar 29 '21 at 22:37
  • Yes that's what I mean. SVG is very suitable for drawing x-y graphs. But yes text labels are a pain to render. It's one reason why people use D3 - which has a lot of the functionality people want for charts. – Michael Mullany Mar 29 '21 at 22:43
  • aight. Yeah totally, a real pain. But I guess that your solution's pretty much the only way then, cheers brother! – DevelJoe Mar 29 '21 at 23:00
  • apologies for the follow-up question, but you seem to be a pro in svg, so I thought why not try: do you have an approach that you recommend to get any SVG's coordinates, like the four rectangle's coordinates? With this, I'd be able to do everything I still need, would be perfect to know that! (I need to do some rotations, so being able to calculate the center point of elements precisely would allow to rotate perfectly; hence the question). – DevelJoe Mar 29 '21 at 23:12
  • I'd need to support for IE too, so getBBox is not an option* – DevelJoe Mar 29 '21 at 23:19
  • any SVG's Element's coordinates* – DevelJoe Mar 29 '21 at 23:22