change SVG text to css word wrapping

后端 未结 4 769
星月不相逢
星月不相逢 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 13:58

    This is a sample code to word-wrap texts with D3:

    var nodes = [
        {title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"}
    ]
    
    var w = 960, h = 800;
    
    var svg = d3.select("body").append("svg")
        .attr("width", w)
        .attr("height", h);
    
    var vSeparation = 13, textX=200, textY=100, maxLength=20
    
    var textHolder = svg.selectAll("text")
        .data(nodes)
        .enter().append("text")
        .attr("x",textX)
        .attr("y",textY)
        .attr("text-anchor", "middle")
        .each(function (d) {
            var lines = wordwrap(d.title, maxLength)
    
            for (var i = 0; i < lines.length; i++) {
                d3.select(this).append("tspan").attr("dy",vSeparation).attr("x",textX).text(lines[i])
            }
        });
    
    
    function wordwrap(text, max) {
        var regex = new RegExp(".{0,"+max+"}(?:\\s|$)","g");
        var lines = []
    
        var line
        while ((line = regex.exec(text))!="") {
            lines.push(line);
        } 
    
        return lines
    }
    

提交回复
热议问题