5

In v3 I used drag origin to prevent a noticeable jump due to the mouse-position/element-coordinates offset. Is there an alternative in v4 as the origin function has been removed?

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

    var drag2 = d3.behavior.drag()
            .origin(function () {
                var t = d3.select(this);
                return { x: t.attr("x"), y: t.attr("y") };
            })
            .on("drag", function (d, i) {
                d3.select(this)
                .attr("x", d3.event.x)
                .attr("y", d3.event.y);
            });
user3359706
  • 511
  • 1
  • 5
  • 16
  • Perhaps you should listen to drag `start` event, and grab the event's x and y coordinates there? cf. [reference](https://github.com/d3/d3-drag#drag-events) – Mehdi Jul 26 '16 at 21:20

1 Answers1

7

This worked:

var drag = d3.drag()
     .subject(subject)
     .on("start", function () {
         d3.event.sourceEvent.stopPropagation(); // silence other listeners
         if (d3.event.sourceEvent.which == 1)
             dragInitiated = true;
     })


function subject(d) {return { x: 0, y: d3.event.y }};
user3359706
  • 511
  • 1
  • 5
  • 16
  • 1
    yes thanks... same answer expressed a little differently noting the API change http://stackoverflow.com/questions/38650637/how-to-set-the-origin-while-drag-in-d3-js-in-v4 – headwinds Aug 19 '16 at 14:38
  • 1
    Why "x:0" in subject? "x: d3.event.x" is more appropiate in this answer. Thanks anyway, I was getting crazy with the mouse offstet to the drag object... – eleuteron Jul 12 '17 at 06:01