Wrapping Text in D3
To wrap text in D3, you can implement a function that dynamically adds multiple
<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>
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>
This will wrap your text based on the specified character limit within the confines of your
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!