Trimming text to a given pixel width in SVG

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

    There is several variants using d3 and loops for search smaller text that fit. This can be achieved without loops and it work faster. textNode - d3 node.

    clipText(textNode, maxWidth, postfix) {
            const textWidth = textNode.getComputedTextLength();       
            if (textWidth > maxWidth) {
                let text = textNode.textContent;
                const newLength = Math.round(text.length * (1 - (textWidth - maxWidth) / textWidth));
                text = text.substring(0, newLength);
                textNode.textContent = text.trim() + postfix;
            }
        }
    

提交回复
热议问题