将SVG文本转换为CSS文字换行

12
以下代码用于显示Javascript树形图的文本标签。
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; });

这里使用了SVG,它没有自动换行的功能。我该如何将其改为普通段落

,以便我可以使用CSS对其进行换行。我如何将这个文本变成普通文本,而不是SVG文本?

4个回答

15

这是使用 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
}

1
需要进行一些定制,但我喜欢它。它有效地运行。 - Collin Price
1
我成功地修改了你的技巧,使我的X轴标签自动换行。谢谢!另外,@mbostock有一个更复杂的版本WrapLabels可供参考。最终,SVG 2.0将包括自动换行功能。 - Darren Parker

12

你可能想要使用SVG中的foreignObject标签,代码如下:

nodeEnter.append("foreignObject")
    .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)*/
    .attr("width", your_text_width_variable)
    .attr("height", your_text_height_variable)
    .append("xhtml:body")
    .append("p")
    .text(function(d) { return d.name; });

这是由Mike Bostock提供的一份代码片段,对我很有帮助:https://gist.github.com/1424037


我尝试过了,但现在没有文本显示出来。我正在尝试将其应用于http://bl.ocks.org/1249394,这个例子。这就是我问题中的代码来自的地方。它不起作用是因为节点是SVG圆吗? - user1704514
抱歉,应该为foreignObject包含宽度和高度 - 我已经修改了我的答案代码以使其更清晰。 - Matti John
4
foreignObject 似乎是唯一的解决方案,但请注意它不受 IE(惊喜!)支持。 - KOGI
有没有办法用foreignObject模拟text-anchor: middle;的效果? - jlewkovich

0

foreignObject 不被 IE 支持,而 Chrome 不支持其上的过渡效果。如果这些限制可以接受,我建议使用 foreignObject,因为您可以获得 HTML+CSS 的所有格式。

如果您需要支持 IE 或过渡效果,则建议使用 D3 插件,例如 D3plus。它使文本换行非常容易。

d3plus.textwrap()
  .container('selector')
  .draw();

请查看文档以了解其所有功能。


0

你可以使用 D3.js 中的通用函数,将 svg:text 元素中的文本包装为多个 svg:tspan 子元素(每行一个 tspan):

    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);
                }
            }
        });
    }

你可以像这样使用它:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接