Search code examples
svg

Trimming text to a given pixel width in SVG


I'm drawing text labels in SVG. I have a fixed width available (say 200px). When the text is too long, how can I trim it ?

The ideal solution would also add ellipsis (...) where the text is cut. But I can also live without it.


Solution

  • One way to do this is to use a textPath element, since all characters that fall off the path will be clipped away automatically. See the text-path examples from the SVG testsuite.

    Another way is to use CSS3 text-overflow on svg text elements, an example here. Opera 11 supports that, but you'll likely find that the other browsers support it only on html elements at this time.

    You can also measure the text strings and insert the ellipsis yourself with script, I'd suggest using the getSubStringLength method on the text element, increasing the nchars parameter until you find a length that is suitable.