score:8

Accepted answer

i believe this example on jsfiddle solves your problem.

the code is actually your example, just a little bit modified.

there is a new function wordwrap2() that takes care of proper splitting of the names:

function wordwrap2( 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 );
}

then, there is a new important part of the code that, instead of just creating one text label per node, creates this:

  var maxlength = 20;
  var separation = 18;
  var textx = 0;
  nodeenter.append("text")
      .attr("dy", "0.3em")
      .each(function (d) {
          var lines = wordwrap2(d.name, maxlength).split('\n');
          console.log(d.name);
          console.log(lines);
          for (var i = 0; i < lines.length; i++) {
              d3.select(this)
                .append("tspan")
                .attr("dy", separation)
                .attr("x", textx)
                .text(lines[i]);
           }
    });

(variable maxlength - length used for criterium for splitting names)

(variable separation - visual vertical distance between split lines of a name)

for example this would be the output for maxlength=20:

maxlength=20

this would be the output for maxlength=15: (notice that aspect ratio banker became aspect ratio/banker)

maxlength=15

this would be the output for maxlength=10: (now, check out aspect/ratio/banker !)

maxlength=10

and this would be the output for maxlength=10 and separation=30 (a little more space between individual lines):

maxlength=10 separation=30


Related Query