Breaking text from json into several lines for displaying labels in a D3 force layout

前端 未结 1 1958
你的背包
你的背包 2020-12-18 14:45

I am new to d3.js and coding in general. This is my question:

I am trying to find a way to break long displayed names of force layout objects in lines.

相关标签:
1条回答
  • 2020-12-18 15:30

    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

    0 讨论(0)
提交回复
热议问题