如何在d3和dagre-d3中查找节点上标签的宽度和高度

时间:2016-07-15 22:03:00

标签: javascript jquery angularjs d3.js dagre-d3

我已经工作了一段时间,从d3节点获取标签的宽度和高度。我在节点上有一个图标,用于切换子图。但我需要根据标签的大小动态设置节点的宽度和高度。一旦我得到标签的宽度,我就可以为图标腾出空间。标签尺寸可能会改变,所以我需要知道宽度。这就是我所拥有的,我使用dagre-d3来定位和渲染节点:

 nodes = [
   {id: 1, shape: "diamond", label: "Start"}
  ]

 for (var i = 0; i < nodes.length; i++) {
    g.setNode(nodes[i].id, {
     label: nodes[i].label
      width: // I want to set the width here based on the width of the   label
    });
}

一直在努力,任何帮助都非常感谢。很高兴在需要时显示更多代码。

更新:

以下是我要做的每个节点的文本:

 svgGroup.selectAll("tspan").each(function (object:any) {

      object = parseInt(object, 10) // gives me the id of each node
      var nodeObject = g.node(object); // get the full node 
      var length = this.getComputedTextLength();
      for (var i = 0; i < nodes.length; i++) {
                if (node[i].id === object) {
                     // add the node label width to the nodes array
                     nodes[i].labelWidth = length; 
                  }
          }
 }

以上允许我根据标签+切换图标设置节点的宽度。我遇到的一个问题是,如果一个节点有一个子图,我注意到“svgGroup.selectAll(”tspan“)”只是获得顶级节点。例如,我的节点如下所示:

  this.nodes = [

      {id: 1, shape: "ellipse", label: "start", 
         subGraph: {
               nodes = [
                    {id: 10, shape: "ellipse", label: "SubNode1"},
                    {id: 11, shape: "ellipse", label: "SubNode2"}
                ],
                edges = [
                     {from: 10, to: 11, type: "vee", label: ""}
                 ]
              }
           },
      {id: 2, shape: "rect", label: "Square"}
  ]

“svgGroup.selectAll”语句只获取id为1且id为2的顶级节点的tspan。是否有办法获取id为10且id为11的subGraph节点的tspan。因为id 10或11可以可能有一个嵌套在其中的subGraph,如果是这种情况我也需要获得这些节点的标签宽度。

0 个答案:

没有答案