D3.js 在“有界力”布局中,链接节点超出矩形

D3.js 在“有界力”布局中,链接节点超出矩形,d3.js,D3.js,我正在尝试将拖动的节点绑定到布局中 我用以下代码修改了示例: function dragstarted() { if (!d3.event.active) simulation.alphaTarget(0.3).restart(); d3.event.subject.fx = Math.max(10, Math.min(width - 10, d3.event.subject.x)) ; d3.event.subject.fy = Math.max(10, Math.min(heig

我正在尝试将拖动的节点绑定到布局中

我用以下代码修改了示例:

function dragstarted() {
  if (!d3.event.active) simulation.alphaTarget(0.3).restart();
  d3.event.subject.fx = Math.max(10, Math.min(width - 10, d3.event.subject.x)) ;
  d3.event.subject.fy = Math.max(10, Math.min(height - 10, d3.event.subject.y)) ;
}

function dragged() {
  d3.event.subject.fx = Math.max(10, Math.min(width - 10, d3.event.x));
  d3.event.subject.fy = Math.max(10, Math.min(height - 10, d3.event.y));
}

function dragended() {
  if (!d3.event.active) simulation.alphaTarget(0);
  //d3.event.subject.fx = null;
  //d3.event.subject.fy = null;
}
上述更改允许节点粘贴,拖动的节点保持在矩形内,但是,链接的节点超出了矩形

我指的是示例,因为它在SVG中,所以我无法确定如何阻止链接节点(连接到拖动的节点)从布局中退出


这里SVG和canvas之间的区别相对容易修复

在链接中,勾选函数使用元素的绑定数据(数据数组中的对象)为每个svg元素执行一些逻辑:

  function tick() {

    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });
     ...
  function ticked() {

    graph.nodes.forEach(function(d) { 
      d.x = Math.max(margin, Math.min(width - margin, d.x))
      d.y = Math.max(margin, Math.min(height - margin, d.y))
    })
...
由于我们没有可以使用的元素,因此我们可以只操作原始数据数组:

  function tick() {

    node.attr("cx", function(d) { return d.x = Math.max(radius, Math.min(width - radius, d.x)); })
        .attr("cy", function(d) { return d.y = Math.max(radius, Math.min(height - radius, d.y)); });
     ...
  function ticked() {

    graph.nodes.forEach(function(d) { 
      d.x = Math.max(margin, Math.min(width - margin, d.x))
      d.y = Math.max(margin, Math.min(height - margin, d.y))
    })
...
下面是一个使用拖动函数和原始force canvas示例的示例