How to either determine SVG text box width, or force line breaks after 'x' characters?

后端 未结 5 1398
猫巷女王i
猫巷女王i 2020-12-04 15:00

I\'m creating an SVG text box using the Raphael library, and filling it with a dynamic string which is extracted from an XML document.

Sometimes, this string is long

5条回答
  •  我在风中等你
    2020-12-04 15:15

    thanks for the answer. However, I found that I needed a few adjustments to work for me:

    function textWrap(t, width) {
        var content = t.attr("text");
        var abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        t.attr({
          'text-anchor' : 'start',
          "text" : abc
        });
        var letterWidth = t.getBBox().width / abc.length;
        t.attr({
            "text" : content
        });
    
        var words = content.split(" ");
        var x = 0, s = [];
        for ( var i = 0; i < words.length; i++) {
    
            var l = words[i].length;
            if (x + (l * letterWidth) > width) {
                s.push("\n");
                x = 0;
            }
            x += l * letterWidth;
            s.push(words[i] + " ");
        }
        t.attr({
            "text" : s.join("")
        });
    }
    

    The changes were:

    • the comparison needed to use (l * letterwidth) ... not just l
    • the if/else changed to just an if - so that a line break will always set X to 0
    • and always add the new l * letterwidth to the x value

    hope this helps.

提交回复
热议问题