javascript - D3js 外部限制

标签 javascript d3.js

我想将缩放监听器(缩放)与翻译结合使用,以将所有节点、文本和路径很好地放入 viewport/d3 容器中。

我将树布局与强制布局结合使用。

有没有办法获取所有对象的外部限制(对象周围不存在的矩形,具有矩形的高度/宽度和 X+y 位置)?这样我就可以使用翻译/缩放来很好地适应一切。

最佳答案

我尝试了几种方法来解决这个问题。我通过 D3 尝试了 getBoundingClientRect() 和 getBBox() 但都没有给出正确的坐标。

所以我所做的就是循环遍历每个圆圈并查看它的数据。我有一些逻辑来获取最低的左值、最高的右值、最低的顶部值和最高的底部值。

为此,我只是使用了以下逻辑:

 var thisNodeData = allNodes[i].__data__;

    var thisLeft = thisNodeData.x;
    var thisRight = thisNodeData.x;
    var thisTop = thisNodeData.y;
    var thisBottom = thisNodeData.y;

    if (i == 0) { //set it on first one
      left = thisLeft;
      right = thisRight;
      top = thisTop;
      bottom = thisBottom;
    };
    //overwrite values where needed
    if (left > thisLeft) {
      left = thisLeft
    }
    if (right < thisRight) {
      right = thisRight
    }
    if (top > thisTop) {
      top = thisTop
    }
    if (bottom < thisBottom) {
      bottom = thisBottom
    }

现在这些左、右、下和上的值将是你的矩形的值。但是,这种方式可以获得每个圆的中心点,因此为了弥补这一点,我编写了一个半径值,但这可以通过编程方式找到:

所以我用它们创建了一个像这样的矩形:

var circleRadius = 20;
  var rectAttr = [{
    x: top - circleRadius / 2,
    y: left - circleRadius / 2,
    width: bottom - top + circleRadius,
    height: right - left + circleRadius,
  }]

I must say, I messed about this these values. You would think that x would be left, y would be top but this didn't get the correct outcome. If anyone can tell me what I have done wrong here, will be appreciated. But for now this works fine, it just doesn't seem like the correct logic.

现在使用 rectAttr 创建边界矩形:

 svg.selectAll('rectangle')
    .data(rectAttr)
    .enter() //.append('svg')
    .append('rect')
    .attr('x', function(d) {
      return d.x; 
    })
    .attr('y', function(d) {
      return d.y; 
    })
    .attr('width', function(d) {
      return d.width; 
    })
    .attr('height', function(d) {
      return d.height; 
    })
    .style('stroke', 'red').style('fill', 'none')

我已添加此函数,以便在单击节点时调用,以便我可以向您展示它的工作原理。

更新了 fiddle :http://jsfiddle.net/thatOneGuy/JnNwu/916/

编辑:

现在根据大小进行缩放。

这里你要做的是获得新矩形与旧矩形的比例差异。

首先,我从矩形的宽度和高度中获得最大值,以给出正确的比例,如下所示:

var testScale = Math.max(rectAttr[0].width,rectAttr[0].height)
var widthScale = width/testScale
var heightScale = height/testScale 
var scale = Math.max(widthScale,heightScale);

然后在翻译中使用这个比例。要放大矩形,您只需获取中心点并相应地调整它,如下所示:

var transX = -(parseInt(d3.select('#invisRect').attr("x")) + parseInt(d3.select('#invisRect').attr("width"))/2) *scale + width/2;
var transY = -(parseInt(d3.select('#invisRect').attr("y")) + parseInt(d3.select('#invisRect').attr("height"))/2) *scale + height/2;

return 'translate(' + transX + ','+ transY + ')scale('+scale+')' ;

我还添加了这一行:

d3.select('#invisRect').remove();

在创建一个新矩形之前,否则在获取上面的平移尺寸时我会得到错误的矩形。

最终工作 fiddle :http://jsfiddle.net/thatOneGuy/JnNwu/919/

var json = {
  "name": "Base",
  "children": [{
    "name": "Type A",
    "children": [{
      "name": "Section 1",
      "children": [{
        "name": "Child 1"
      }, {
        "name": "Child 2"
      }, {
        "name": "Child 3"
      }]
    }, {
      "name": "Section 2",
      "children": [{
        "name": "Child 1"
      }, {
        "name": "Child 2"
      }, {
        "name": "Child 3"
      }]
    }]
  }, {
    "name": "Type B",
    "children": [{
      "name": "Section 1",
      "children": [{
        "name": "Child 1"
      }, {
        "name": "Child 2"
      }, {
        "name": "Child 3"
      }]
    }, {
      "name": "Section 2",
      "children": [{
        "name": "Child 1"
      }, {
        "name": "Child 2"
      }, {
        "name": "Child 3"
      }]
    }]
  }]
};

var width = 700;
var height = 650;
var maxLabel = 150;
var duration = 500;
var radius = 5;

var i = 0;
var root;

var tree = d3.layout.tree()
  .size([height, width]);

var diagonal = d3.svg.diagonal()
  .projection(function(d) {
    return [d.y, d.x];
  });

var svg = d3.select("body").append("svg")
  .attr("width", width)
  .attr("height", height)
  .append("g")
  .attr("transform", "translate(" + maxLabel + ",0)");

root = json;
root.x0 = height / 2;
root.y0 = 0;

root.children.forEach(collapse);

function update(source) {
  // Compute the new tree layout.
  var nodes = tree.nodes(root).reverse();
  var links = tree.links(nodes);

  // Normalize for fixed-depth.
  nodes.forEach(function(d) {
    d.y = d.depth * maxLabel;
  });

  // Update the nodes…
  var node = svg.selectAll("g.node")
    .data(nodes, function(d) {
      return d.id || (d.id = ++i);
    });

  // Enter any new nodes at the parent's previous position.
  var nodeEnter = node.enter()
    .append("g")
    .attr("class", "node")
    .attr("transform", function(d) {
      return "translate(" + source.y0 + "," + source.x0 + ")";
    })
    .on("click", click);

  nodeEnter.append("circle").attr('class', 'circleNode')
    .attr("r", 0)
    .style("fill", function(d) {
      return d._children ? "lightsteelblue" : "white";
    });

  nodeEnter.append("text")
    .attr("x", function(d) {
      var spacing = computeRadius(d) + 5;
      return d.children || d._children ? -spacing : spacing;
    })
    .attr("dy", "3")
    .attr("text-anchor", function(d) {
      return d.children || d._children ? "end" : "start";
    })
    .text(function(d) {
      return d.name;
    })
    .style("fill-opacity", 0);

  // Transition nodes to their new position.
  var nodeUpdate = node.transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + d.y + "," + d.x + ")";
    });

  nodeUpdate.select("circle")
    .attr("r", function(d) {
      return computeRadius(d);
    })
    .style("fill", function(d) {
      return d._children ? "lightsteelblue" : "#fff";
    });

  nodeUpdate.select("text").style("fill-opacity", 1);

  // Transition exiting nodes to the parent's new position.
  var nodeExit = node.exit().transition()
    .duration(duration)
    .attr("transform", function(d) {
      return "translate(" + source.y + "," + source.x + ")";
    })
    .remove();

  nodeExit.select("circle").attr("r", 0);
  nodeExit.select("text").style("fill-opacity", 0);

  // Update the links…
  var link = svg.selectAll("path.link")
    .data(links, function(d) {
      return d.target.id;
    });

  // Enter any new links at the parent's previous position.
  link.enter().insert("path", "g")
    .attr("class", "link")
    .attr("d", function(d) {
      var o = {
        x: source.x0,
        y: source.y0
      };
      return diagonal({
        source: o,
        target: o
      });
    });

  // Transition links to their new position.
  link.transition()
    .duration(duration)
    .attr("d", diagonal);

  // Transition exiting nodes to the parent's new position.
  link.exit().transition()
    .duration(duration)
    .attr("d", function(d) {
      var o = {
        x: source.x,
        y: source.y
      };
      return diagonal({
        source: o,
        target: o
      });
    })
    .remove();

  // Stash the old positions for transition.
  nodes.forEach(function(d) {
    d.x0 = d.x;
    d.y0 = d.y;
  });
}

function computeRadius(d) {
  if (d.children || d._children) return radius + (radius * nbEndNodes(d) / 10);
  else return radius;
}

function nbEndNodes(n) {
  nb = 0;
  if (n.children) {
    n.children.forEach(function(c) {
      nb += nbEndNodes(c);
    });
  } else if (n._children) {
    n._children.forEach(function(c) {
      nb += nbEndNodes(c);
    });
  } else nb++;

  return nb;
}

function click(d) {

  if (d.children) {
    d._children = d.children;
    d.children = null;
  } else {
    d.children = d._children;
    d._children = null;
  }
  update(d);
  getBoundingBox();
}

function collapse(d) {
  if (d.children) {
    d._children = d.children;
    d._children.forEach(collapse);
    d.children = null;
  }
}

update(root);
getBoundingBox();

function getBoundingBox() {
  var left = 0,
    right = 0,
    top = 0,
    bottom = 0;

  var allNodes = document.getElementsByTagName('circle');


  for (var i = 0; i < allNodes.length; i++) {

    var thisNodeData = allNodes[i].__data__;

    var thisLeft = thisNodeData.x;
    var thisRight = thisNodeData.x;
    var thisTop = thisNodeData.y;
    var thisBottom = thisNodeData.y;

    if (i == 0) { //set it on first one
      left = thisLeft;
      right = thisRight;
      top = thisTop;
      bottom = thisBottom;
    };
    //overwrite values where needed
    if (left > thisLeft) {
      left = thisLeft
    }
    if (right < thisRight) {
      right = thisRight
    }
    if (top > thisTop) {
      top = thisTop
    }
    if (bottom < thisBottom) {
      bottom = thisBottom
    }

  }
  var circleRadius = 20;
  var rectAttr = [{
    x: top - circleRadius / 2,
    y: left - circleRadius / 2,
    width: bottom - top + circleRadius,
    height: right - left + circleRadius,
  }]
d3.select('#invisRect').remove();
  svg.selectAll('rectangle')
    .data(rectAttr)
    .enter() //.append('svg')
    .append('rect').attr('id','invisRect')
    .attr('x', function(d) {
      return d.x; 
    })
    .attr('y', function(d) {
      return d.y; 
    })
    .attr('width', function(d) {
      return d.width; 
    })
    .attr('height', function(d) {
      return d.height; 
    })
    .style('stroke', 'red').style('fill', 'none')
      
svg.attr('transform',function(d){
var testScale = Math.max(rectAttr[0].width,rectAttr[0].height)
var widthScale = width/testScale
var heightScale = height/testScale 
var scale = Math.max(widthScale,heightScale);
 
var transX = -(parseInt(d3.select('#invisRect').attr("x")) + parseInt(d3.select('#invisRect').attr("width"))/2) *scale + width/2;
var transY = -(parseInt(d3.select('#invisRect').attr("y")) + parseInt(d3.select('#invisRect').attr("height"))/2) *scale + height/2;
 
return 'translate(' + transX + ','+ transY + ')scale('+scale+')' ;
})




}
html {
  font: 10px sans-serif;
}

svg {
  border: 1px solid silver;
}

.node {
  cursor: pointer;
}

.node circle {
  stroke: steelblue;
  stroke-width: 1.5px;
}

.link {
  fill: none;
  stroke: lightgray;
  stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id=tree></div>

关于javascript - D3js 外部限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37340215/

相关文章:

javascript - 获取 Typescript 以推断联合类型

javascript - 使用 RxJS 限制异步请求

javascript - 使用 D3 更改 shapefile 投影以进行可视化

javascript - 使用 D3.JS 在同一个 SVG 上放置多组圆

javascript - CSS 关键帧动画在某些浏览器中无法运行

javascript - jquery协助获取ms-vb2的子字符串

javascript - 如何在tabpanel中动态隐藏和显示选项卡

javascript - 跨浏览器d3.js SVG线条渲染日期排序

javascript - D3 使用图案用图像填充形状

javascript - d3js :The xaxis time is not showing the complete date value