user2179256
user2179256

Reputation: 749

SVG get text characters bounds in Javascript

Is there any way to get the bounds of each character in svg using Javascript?

Note: All the text are in svg text elements (Not Tspan ... etc)

Upvotes: 1

Views: 870

Answers (1)

Robert Longson
Robert Longson

Reputation: 124059

There's an SVG DOM method called getExtentOfChar that will get you the bounding box of each character.

Pass in the index of the character you want to get, 0 for the first character etc.

var t = document.getElementById("t");
alert(t.getExtentOfChar(0).width + " " + t.getExtentOfChar(3).width);
<svg>
  <text id="t" y="20">hello</text>
</svg>

Upvotes: 4

Related Questions