Reputation: 119
I wish to use newline characters for the node text in the following code:
http://jsfiddle.net/cyril123/0vbtvoon/22/
I would like the text to have a new line for each word. For example, 'Joe Bloggs' would become 'Joe \nBloggs' where \n is the line break.
The problem lies on line 184 of the javascript with:
nodes.append("text")
.text(function (d) {
return d.name;
})
I cannot work out how to cause a line break for node text. What is the best way to achieve this?
Upvotes: 2
Views: 2885
Reputation: 865
Unfortunately, you will have to write a function to manually break out the text into separate lines. Mike Bostock has a nice function written already though:
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).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", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
Upvotes: 4