Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
D3.js 如何在强制布局中拖动时将svg元素捕捉到网格_D3.js_Svg - Fatal编程技术网

D3.js 如何在强制布局中拖动时将svg元素捕捉到网格

D3.js 如何在强制布局中拖动时将svg元素捕捉到网格,d3.js,svg,D3.js,Svg,我得到了d3.js force布局,其中节点是带有关联文本的矩形。每当拖动节点时,位置都是固定的,就像mike的一样 我希望节点在拖动时捕捉到不可见的栅格。使它们整齐地对齐。因此,我在拖动事件中添加了以下内容: var grid = 50; d3.select(this) .attr("x", function(d) { return Math.round(d3.event.x/grid)*grid; }) .attr("y", function(d) { return Math.rou

我得到了d3.js force布局,其中节点是带有关联文本的矩形。每当拖动节点时,位置都是固定的,就像mike的一样

我希望节点在拖动时捕捉到不可见的栅格。使它们整齐地对齐。因此,我在拖动事件中添加了以下内容:

var grid = 50;
d3.select(this)
  .attr("x", function(d) { return Math.round(d3.event.x/grid)*grid; })
  .attr("y", function(d) { return Math.round(d3.event.y/grid)*grid; });
不知何故,这并不像预期的那样有效。我猜这和力布局的勾号功能有关。但我不确定,因此force.stop()、force.start()调用以查看这是否有帮助

我还尝试将rect和text嵌套在g元素中,并使用transform(translate)来定位节点。但也没有成功。

节点的坐标取自节点数组中每个数据点的d.x和d.y,因此,尽管您更新了屏幕元素的x和y属性,但下一个勾号会将其重置为d.x和d.y,使您在演示中看到的移动很小(尽管在节点固定后,该点不会再次移动)

您需要离散节点位置数据-d.x和d.y-而不仅仅是节点DOM元素的位置属性,对于固定节点来说,这似乎是通过d.px和d.py-之前的节点坐标来完成的。勾选中的固定节点似乎通过将它们设置为d.px和d.py()来计算d.x和d.y

function dblclick(d) {
  d3.select(this).classed("fixed", d.fixed = false);
}

function dragstarted(d) {
  d3.select(this)
    .classed("fixed", d.fixed = true);
}

function dragged(d,i) {
  //force.stop();
  var grid = 50;

  var nx = Math.round(d3.event.x/grid)*grid;
  var ny = Math.round(d3.event.y/grid)*grid;

  d.px = nx;
  d.py = ny;
}

function dragended(d) {
  //force.start();
  console.log(this);
}