Trimming text to a given pixel width in SVG

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

提交回复
热议问题