将文本从json分成几行,用于在D3强制布局中显示标签

 william浩浩_597 发布于 2023-02-07 18:43

我是d3.js的新手和编码.这是我的问题:

我试图找到一种方法来打破行中强制布局对象的长显示名称.

我希望能够确定在哪里打破这些行,我猜这是可以从json文件中完成的事情.

我知道已经有类似的问题已经提出,但我找不到放置代码的位置或为什么我以前的尝试没有成功.这是我的代码:

var width = 960,
    height = 800,
    root;

var force = d3.layout.force()
    .linkDistance(120)
    .charge(-600)
    .gravity(.06)
    .size([width, height])
    .on("tick", tick);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var link = svg.selectAll(".link"),
    node = svg.selectAll(".node");

d3.json("graph.json", function(error, json) {
  root = json;
  update();
});

function update() {
  var nodes = flatten(root),
      links = d3.layout.tree().links(nodes);


  // Restart the force layout.
  force
      .nodes(nodes)
      .links(links)
      .start();

  // Update links.
  link = link.data(links, function(d) { return d.target.id; });

  link.exit().remove();

  link.enter().insert("line", ".node")
      .attr("class", "link");

  // Update nodes.
  node = node.data(nodes, function(d) { return d.id; });

  node.exit().remove();

  var nodeEnter = node.enter().append("g")  
      .attr("class", "node")
      .on("click", click)
      .call(force.drag);

  nodeEnter.append("circle")
      .attr("r", function(d) { return Math.sqrt(d.size) / 3 || 10; });

  nodeEnter.append("text")
      .attr("dy", "0.3em")
      .text(function(d) { return d.name; });

  node.select("circle")
      .style("fill", color);
}

// Divide text

text.append("text")       
    .each(function (d) {
    var arr = d.name.split(" ");
    if (arr != undefined) {
        for (i = 0; i < arr.length; i++) {
            d3.select(this).append("tspan")
                .text(arr[i])
                .attr("dy", i ? "1.2em" : 0)
                .attr("x", 0)
                .attr("text-anchor", "middle")
                .attr("class", "tspan" + i);
        }
    }
});

// Divide text

function tick() {
  link.attr("x1", function(d) { return d.source.x; })
      .attr("y1", function(d) { return d.source.y; })
      .attr("x2", function(d) { return d.target.x; })
      .attr("y2", function(d) { return d.target.y; });

  node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
}

function color(d) {
  return d._children ? "#9ecae1" // collapsed package
      : d.children ? "#ffffff" // expanded package
      : "#ffcc50"; // leaf node
}


// Toggle children on click.
function click(d) {
  if (d3.event.defaultPrevented) return; // ignore drag
  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else if (d._children) {
    d.children = d._children;
    d._children = null;
  } else {
    // This was a leaf node, so redirect.
    window.open(d.url, 'popUpWindow','height=600,);
  }
  update();
}

// Returns a list of all nodes under the root.
function flatten(root) {
  var nodes = [], i = 0;

  function recurse(node) {
    if (node.children) node.children.forEach(recurse);
    if (!node.id) node.id = ++i;
    nodes.push(node);
  }

  recurse(root);
  return nodes;
}

这是json信息:

{
 "name": "flare",
 "children": [
  {
   "name": "analytics",
   "children": [
    {
     "name": "cluster",
     "children": [
      {"name": "Agglomerative Cluster", "size": 3938},
      {"name": "Community Structure", "size": 3812},
      {"name": "Hierarchical Cluster", "size": 6714},
      {"name": "Merge Edge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "Betweenness Centrality", "size": 3534},
      {"name": "Link Distance", "size": 5731},
      {"name": "Max Flow Min Cut", "size": 7840},
      {"name": "Shortest Paths", "size": 5914},
      {"name": "Spanning Tree", "size": 3416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "Aspect Ratio Banker", "size": 7074}
     ]
    }
   ]
  }
 ]

例如,我希望能够决定打破Aspect/Ratio Banker或Aspect Ratio/Banker.

1 个回答
  • 我相信这个关于jsfiddle的例子解决了你的问题.

    代码实际上是你的例子,只是稍作修改.

    有一个新的函数wordwrap2()负责正确拆分名称:

    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 );
    }
    

    然后,代码中有一个新的重要部分,而不是仅为每个节点创建一个文本标签,而是创建:

      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]);
               }
        });
    

    (变量maxLength - 用于分割名称的标准的长度)

    (变量分隔 - 名称分割线之间的视觉垂直距离)

    例如,这将是maxLength = 20的输出:

    最大长度= 20

    这将是maxLength = 15的输出:(请注意,Aspect Ratio Banker成为纵横比/银行家)

    最大长度= 15

    这将是maxLength = 10的输出:(现在,请查看Aspect/Ratio/Banker!)

    最大长度= 10

    这将是maxLength = 10和separator = 30的输出(各行间距更多):

    maxLength = 10分离= 30

    2023-02-07 18:45 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有