Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trimming text to a given pixel width in SVG

Tags:

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.

like image 583
Blacksad Avatar asked Feb 11 '12 15:02

Blacksad


2 Answers

Using d3 library

a wrapper function for overflowing text:

    function wrap() {         var self = d3.select(this),             textLength = self.node().getComputedTextLength(),             text = self.text();         while (textLength > (width - 2 * padding) && text.length > 0) {             text = text.slice(0, -1);             self.text(text + '...');             textLength = self.node().getComputedTextLength();         }     }  

usage:

text.append('tspan').text(function(d) { return d.name; }).each(wrap); 
like image 93
user2846569 Avatar answered Sep 28 '22 11:09

user2846569


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.

like image 40
Erik Dahlström Avatar answered Sep 28 '22 09:09

Erik Dahlström