As I dive into the world of d3.js, my current project involves creating a network graph where each circle must contain a label.
I am specifically looking for a way to include line breaks in an SVG text element.
My approach so far has been to divide the text into multiple <tspan>
s, setting x="0" and varying "y" values to mimic separate lines. However, the code I've implemented is yielding unexpected results.
var text = svg.selectAll("text").data(force.nodes()).enter().append("text");
text
.text(function (d) {
arr = d.name.split(" ");
var arr = d.name.split(" ");
if (arr !== undefined) {
for (i = 0; i < arr.length; i++) {
text.append("tspan")
.text(arr[i])
.attr("class", "tspan" + i);
}
}
});
In this snippet, I break down the text string by spaces and assign each segment to a tspan element. However, the issue arises where text from one circle appears in all circles. How can I resolve this problem?
For reference, check out this JSFIDDLE http://jsfiddle.net/xhNXS/ with only SVG text.
Additionally, here is another JSFIDDLE http://jsfiddle.net/2NJ25/16/ that showcases the problematic behavior with tspan elements.