1

I am struggling to wrap long text in a d3 collapsible tree. I used the code in this answer and it seems to be working fine as long as the text gets split into 2 lines but something weird is happening when the text gets split into more than 2 lines.

As you can see in the image below, the third line is weirdly spaced. When I inspect the text element the dy property seems to be fine (0 for line1, 1 for line2 and 2 for line3) so I am not able to figure out what's wrong. enter image description here

I am using .call(wrap, 250); when calling the function, if that's helpful.

Here's the wrap function that I am using from the linked answer above.

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

0 Answers0