在 d3.js 中换行长文本

Wrapping long text in d3.js

我想将长文本元素换行到一定宽度。这里的例子取自Bostock's wrap function,但似乎有两个问题:首先wrap的结果没有继承元素的x值(文本向左​​移动);其次它在同一行换行,lineHeight 参数无效。

感谢您的建议。 http://jsfiddle.net/geotheory/bk87ja3g/

var svg = d3.select("body").append("svg")
    .attr("width", 300)
    .attr("height", 300)
    .style("background-color", '#ddd');

dat = ["Ukip has peaked, but no one wants to admit it - Nigel Farage now resembles every other politician", 
       "Ashley Judd isn't alone: most women who talk about sport on Twitter face abuse",
       "I'm on list to be a Mars One astronaut - but I won't see the red planet"];

svg.selectAll("text").data(dat).enter().append("text")
    .attr('x', 25)
    .attr('y', function(d, i){ return 30 + i * 90; })
    .text(function(d){ return d; })
    .call(wrap, 250);

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 1,
        lineHeight = 1.2, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.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 = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
            }
        }
    });
}

Bostock 的原始函数假定 text 元素具有初始 dy 集。它还会删除 text 上的任何 x 属性。最后,您将 wrap 函数更改为从 lineNumber = 1 开始,需要 0.

稍微重构一下:

function wrap(text, width) {
    text.each(function() {
        var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0, //<-- 0!
        lineHeight = 1.2, // ems
        x = text.attr("x"), //<-- include the x!
        y = text.attr("y"),
        dy = text.attr("dy") ? text.attr("dy") : 0; //<-- null check
        tspan = text.text(null).append("tspan").attr("x", x).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 = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
            }
        }
    });
}

已更新 fiddle

问题出在这一行:

dy = parseFloat(text.attr("dy"))

在您链接到的示例中,dy 是在 text 元素上设置的,但在您的情况下不是。所以你在那里得到 NaN,这反过来导致 tspandyNaN。如果 NaN:

,则通过将 0 分配给 dy 来修复
dy = parseFloat(text.attr("dy")) || 0

完成演示 here