d3点击时拖动到其他位置 - 原点?

时间:2015-07-13 19:22:04

标签: javascript d3.js

尝试拖动群组。为什么起源不起作用?注意第一次点击它时它是如何跳跃的? JSFIDDLE基于此:http://bl.ocks.org/mbostock/1557377

var drag = d3.behavior.drag() // construct drag behavior
.origin(function() { 
    var t = d3.select(this);
    return {x: t.attr("x"), y: t.attr("y")};
})
.on("drag", function(d,i) {
    d.x += d3.event.dx
    d.y += d3.event.dy
    d3.select(this).attr("transform", function(d,i){
        return "translate(" + [ d.x,d.y ] + ")"
    })
});

1 个答案:

答案 0 :(得分:2)

您正在混合设置位置的不同方式 - 您正在设置transformcx以及cy on the circles, but not on the g elements that you want to drag. While it can be made to work by computing the various offsets, it's much easier if you set the position for the things you're interested in (i.e. the g`元素并且调用了拖动行为。

var svgG = svg.append("g")
  .attr("transform", function(d) { return "translate(" + [ d.x,d.y ] + ")"; })
  .call(drag);

完整示例here