javascript - Create line break in D3 -
i making tree map () , want create line break when text longer 10 characters.
therefore this
would this
first use method spitting string @ 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 d3 generating text @ 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 have entered wordwrap method d3 code. show
tag within actual text of tree graph.
how can split text based on length d3 newlines string if above 10 characters.
at point noticed "< br>" doesn't work inside svg:text element see 2 ways of accomplishing need:
- using svg textarea
- including svg tspan whenever want add line break.
for first method at: https://www.w3.org/tr/svgtiny12/text.html#textareaelement
all need define text area size , let svg handle characters. may want resize text make way fits need.
for second method at: https://www.w3.org/tr/svg/text.html#tspanelement
in case must include logic append tspan [append('svg:tspan')] inside svg:text element whenever want line break.
you have change logic of nodeenter.append not difficult accomplish either way.
Comments
Post a Comment