简体   繁体   中英

d3 drag jumping to other position when clicked - origin?

Trying to drag groups. Why doesn't origin work here? Notice how it jumps when you first click on it? JSFIDDLE Based on this: 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 ] + ")"
    })
});

You're mixing different ways of setting positions -- you're setting transform and cx and 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 (ie the 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 (ie the g` elements) and that the drag behaviour is called on.

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

Complete example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM