首页  >  文章  >  web前端  >  如何在 D3 中换行文本以提高树可视化的可读性?

如何在 D3 中换行文本以提高树可视化的可读性?

Barbara Streisand
Barbara Streisand原创
2024-10-25 07:43:02591浏览

How can I wrap text in D3 to improve the readability of my tree visualizations?

在 D3 中换行文本

增强 D3 树的可读性可以涉及换行文本以防止长单词扭曲布局。这可以通过使用来实现。元素,它允许在单个文本块中创建多行。

要实现文本换行,请按照以下步骤操作:

1.创建包装函数

基于 Mike Bostock 的“包装长标签”示例,定义一个名为wrap 的函数,该函数添加 根据指定宽度将元素添加到文本节点:

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

2.应用文本换行

不要直接设置每个节点的文本,而是利用换行功能将文本换行到指定宽度内:

// Add entering nodes in the parent’s old position.
node.enter().append("text")
    .attr("class", "node")
    .attr("x", function (d) { return d.parent.px; })
    .attr("y", function (d) { return d.parent.py; })
    .text("Foo is not a long word")
    .call(wrap, 30);

这会将文本换行30 像素,根据需要创建多行以容纳长单词。

以上是如何在 D3 中换行文本以提高树可视化的可读性?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn