d3-drag and d3-zoom - Mystery Bug

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