d3.js v4拖动缩放元素跳鼠标

时间:2017-03-15 09:21:07

标签: javascript d3.js d3.js-v4

您好Stackoverflow社区!

我有以下问题: 我创建了一个d3力导向图,其中div为节点,并包含d3-zoom行为。 当我缩小或放大很多时,节点的拖动变得太快(放大时)或太慢(缩小时)。 我通过应用d3.mouse(d3.select(“。links”)。node())来修复它,以便从缩放区域内部获取鼠标坐标。

但是,因为我这样做,我注意到拖动节点时此节点会跳转。它以鼠标指针为中心而不是鼠标指针。

经过一些研究后,我尝试通过指定一个类似的主题来解决这个问题:

d3.drag().subject(function() { 
        var t = d3.select(this);
        return {x: parseInt(t.style("left"),10), y: parseInt(t.style("top"),10)};
    })

但它没有任何影响,我现在已经没有想法了。如果有人能在这里帮助我,我很高兴。

跟随小提琴演示问题:https://jsfiddle.net/jxkgfdcm/

1 个答案:

答案 0 :(得分:2)

它跳转到节点的中心,因为在拖动中你正在做:

function dragged(d) {
  var coordinates = [0, 0];
  coordinates = d3.mouse(d3.select(".links").node()); //this will give the link end location..so it will jump to the centre of the node
  var x = coordinates[0];
  var y = coordinates[1];

  d.fx = x;
  d.fy = y;


  d.fixed = true;
}
应该是:

function dragged(d) {

  d.fx += d3.event.dx;//give delta increment to current position
  d.fy += d3.event.dy//give delta increment to current position

  d.fixed = true;
}

工作代码here

相关问题