Trimming text to a given pixel width in SVG

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

    Implementing Erik's 3rd suggestion I came up with something like this:

    //places textString in textObj, adds an ellipsis if text can't fit in width
    function placeTextWithEllipsis(textObj,textString,width){
        textObj.textContent=textString;
    
        //ellipsis is needed
        if (textObj.getSubStringLength(0,textString.length)>=width){
            for (var x=textString.length-3;x>0;x-=3){
                if (textObj.getSubStringLength(0,x)<=width){
                    textObj.textContent=textString.substring(0,x)+"...";
                    return;
                }
            }
            textObj.textContent="..."; //can't place at all
        }
    }
    

    Seems to do the trick :)

    0 讨论(0)
  • 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 );
    
    0 讨论(0)
提交回复
热议问题