Trimming text to a given pixel width in SVG

后端 未结 8 1808
感动是毒
感动是毒 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:46

    @user2846569 show me how to do it ( yes, using d3.js ). But, I have to make some little changes to work:

    
             function wrap( d ) {
                    var self = d3.select(this),
                        textLength = self.node().getComputedTextLength(),
                        text = self.text();
                    while ( ( textLength > self.attr('width') )&& text.length > 0) {
                        text = text.slice(0, -1);
                        self.text(text + '...');
                        textLength = self.node().getComputedTextLength();
                    }
                }
                svg.append('text')
                    .append('tspan')
                    .text(function(d) { return d; }) 
                    .attr('width', 200 )
                    .each( wrap );
    

提交回复
热议问题