首頁  >  文章  >  web前端  >  如何在 D3 中進行字元限製文字換行?

如何在 D3 中進行字元限製文字換行?

Linda Hamilton
Linda Hamilton原創
2024-10-25 07:04:02721瀏覽

How to Wrap Text in D3 with a Character Limit?

在 D3 中換行

要在 D3 中換行,您可以實現動態新增多個 的函數。 元素一定字元限制內的節點:

<code class="javascript">function wrap(text, width) {
  text.each(function () {
    var words = d3.select(this)
      .text()
      .split(/\s+/);

    words = words.reverse();

    var line = [];
    var lineNumber = 0;
    var lineHeight = 1.1; // ems
    var x = text.attr("x");
    var y = text.attr("y");
    var dy = 0; // parseFloat(text.attr("dy"));

    var 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>

然後,您不必直接設定每個節點的文本,而是必須對其調用包裝函數:

<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 中進行字元限製文字換行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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