Skip to content

Instantly share code, notes, and snippets.

@tmsss
Created May 29, 2019 13:10
Show Gist options
  • Save tmsss/c7c36b0917d2e1c13d68a1385bcb809f to your computer and use it in GitHub Desktop.
Save tmsss/c7c36b0917d2e1c13d68a1385bcb809f to your computer and use it in GitHub Desktop.
Wrapping Text in D3
// from https://stackoverflow.com/questions/24784302/wrapping-text-in-d3?lq=1
var wrap = function(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);
}
}
});
};
// 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment