Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

javascript - change SVG text to css word wrapping

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._children ? -8 : -48; }) /*the position of the text (left to right)*/
        .attr("y", 3) /*the position of the text (Up and Down)*/

        .text(function(d) { return d.name; });

This uses svg, which has no word wrapping ability. How do I change this do a normal paragraph

so that I may use css to word wrap it. How do I make this regular text and not svg text?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...