Home > Web Front-end > CSS Tutorial > How to Wrap Text in D3 with a Character Limit?

How to Wrap Text in D3 with a Character Limit?

Linda Hamilton
Release: 2024-10-25 07:04:02
Original
808 people have browsed it

How to Wrap Text in D3 with a Character Limit?

Wrapping Text in D3

To wrap text in D3, you can implement a function that dynamically adds multiple elements to your nodes within a certain character limit:

<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>
Copy after login

Then, instead of directly setting the text of each node, you must call the wrap function on it:

<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>
Copy after login

This will wrap your text based on the specified character limit within the confines of your nodes, allowing them to flow naturally like in the provided example.

The above is the detailed content of How to Wrap Text in D3 with a Character Limit?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template