Trimming text to a given pixel width in SVG

后端 未结 8 1811
感动是毒
感动是毒 2021-02-01 18:14

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

8条回答
  •  情歌与酒
    2021-02-01 18:23

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

提交回复
热议问题