change SVG text to css word wrapping

后端 未结 4 777
星月不相逢
星月不相逢 2020-12-10 13:35

The following code is used to show the text labels of a javascript tree diagram.

nodeEnter.append(\"svg:text\")
        .attr(\"x\", function(d) { return d._         


        
4条回答
  •  被撕碎了的回忆
    2020-12-10 14:02

    You can use this generic function using D3.js to wrap text in an svg:text element into multiple svg:tspan children (one tspan per line):

        function wrapText(text, width) {
            text.each(function () {
                var textEl = d3.select(this),
                    words = textEl.text().split(/\s+/).reverse(),
                    word,
                    line = [],
                    linenumber = 0,
                    lineHeight = 1.1, // ems
                    y = textEl.attr('y'),
                    dx = parseFloat(textEl.attr('dx') || 0), 
                    dy = parseFloat(textEl.attr('dy') || 0),
                    tspan = textEl.text(null).append('tspan').attr('x', 0).attr('y', y).attr('dy', dy + 'em');
    
                while (word = words.pop()) {
                    line.push(word);
                    tspan.text(line.join(' '));
                    if (tspan.node().getComputedTextLength() > width) {
                        line.pop();
                        tspan.text(line.join(' '));
                        line = [word];
                        tspan = textEl.append('tspan').attr('x', 0).attr('y', y).attr('dx', dx).attr('dy', ++linenumber * lineHeight + dy + 'em').text(word);
                    }
                }
            });
        }
    

    You can use it like this:

    svg.selectAll('text').call(wrapText, 100);
    

提交回复
热议问题