首頁  >  文章  >  web前端  >  如何在 D3 樹視覺化中包裝文字標籤以提高可讀性?

如何在 D3 樹視覺化中包裝文字標籤以提高可讀性?

Susan Sarandon
Susan Sarandon原創
2024-10-25 01:10:02714瀏覽

How can I wrap text labels in a D3 tree visualization for improved readability?

在D3 樹中包裹文字

在D3 樹視覺化中,有時需要將文字標籤包裹在節點上以使樹更具可讀性。本文示範如何實現這種文字換行。

挑戰

考慮以下D3 樹:

Foo is not a long word

理想情況下,文本應該換行為:

Foo is
not a
long word

解決方案

要實現文字換行,需要進行兩個關鍵修改:

  1. 建立換行函數:

    實現換行函數,添加 元素節點並控制環繞寬度:

    <code class="javascript">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);
                }
            }
        });
    }</code>
  2. 使用環繞函數:

    不要在每個節點上設定文本,而是應用換行函數:

    <code class="javascript">// 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); // wrap the text in <= 30 pixels</code>

透過實現這些修改,您可以成功地在D3 樹節點上換行文本。

以上是如何在 D3 樹視覺化中包裝文字標籤以提高可讀性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn