I am making a tree map () and want to create a line break when the text is longer than say 10 characters.
Therefore this
would look like this
First I use a method for spitting the string at a specified length:
function wordwrap( str, width, brk, cut ) {
brk = brk || 'n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\S+?(\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk )
}
And here is the D3 for generating text at each node:
nodeEnter.append("svg:text")
.attr("x", function(d) { return d.children || d._children ? -10 : 10; })
.attr("dy", ".35em")
.attr("text-anchor", function(d) { return d.children || d._children ? "end" : "start"; })
.text(function(d) { if(d.name.length > 10) { return wordwrap(d.name, 10, '<br>') } } )
.style("fill-opacity", 1e-6)
.style("fill", "white")
.style("font-size", 22);
You can see that I have entered the wordwrap method into the D3 code. But all it does is show the
tag within the actual text of the tree graph.
How can I split the text based on length so that D3 newlines the string if it is above 10 characters.
tag inside an svg text element. – Mike Atkins Jan 16 '16 at 19:21