d3-drag and d3-zoom - Mystery Bug

I wrote a notebook to show the bug I encounter using d3-zoom and d3-drag: https://observablehq.com/@severo/d3-drag-and-d3-zoom-x-and-y-fields

I don’t understand why the name of the fields in the data attached to the DOM element has an impact on the behavior of the drag.

Note: the reason surely comes from misunderstanding the d3-zoom or d3-drag documentation, but I cannot find which part.

You’ll want to read the documentation for drag.subject:

1 Like

The “not broken” part of your notebook is also a bit broken: if you click on the edge of a circle and drag it, you can see that the circle’s center jumps to be under the pointer.

The solution is to return the projected x,y of the drag subject (the circle’s center in screen coordinates):

for data in {x,y} this gives:

.call(d3.drag().subject(d => {
      const transform = d3.zoomTransform(svg.node());
      const [x, y] = transform.apply([d.x, d.y]);
      return {x,y}
    }).on("drag", dragged));

for data in {xx,yy} this gives:

.call(d3.drag().subject(d => {
      const transform = d3.zoomTransform(svg.node());
      const [x, y] = transform.apply([d.xx, d.yy]);
      return {x,y}
    }).on("drag", dragged));
1 Like

Thanks a lot to both! I updated the notebook with the solution: