Trimming text to a given pixel width in SVG

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

    Try this one, I use this function in my chart library:

    function textEllipsis(el, text, width) {
      if (typeof el.getSubStringLength !== "undefined") {
        el.textContent = text;
        var len = text.length;
        while (el.getSubStringLength(0, len--) > width) {}
        el.textContent = text.slice(0, len) + "...";
      } else if (typeof el.getComputedTextLength !== "undefined") {
        while (el.getComputedTextLength() > width) {
          text = text.slice(0,-1);
          el.textContent = text + "...";
        }
      } else {
        // the last fallback
        while (el.getBBox().width > width) {
          text = text.slice(0,-1);
          // we need to update the textContent to update the boundary width
          el.textContent = text + "...";
        }
      }
    }
    

提交回复
热议问题