Skip to main content
100%

Example of zoom and drag in d3 v4.

✓ Published0🌍 Public
AAlainRo
Last edited Oct 4, 2017
Created on Sep 26, 2017

This example demonstrates how to combine zoom and drag interactions on SVG circles in d3 v4, solving the issue where dragged elements misalign under a zoom transform. It shows 50 randomly positioned circles that remain draggable and correctly track the mouse even when the view is zoomed. The code uses `d3.drag()` and `d3.zoom()` handlers, with a custom drag function that reads the current scale from the circle’s transform attribute to adjust the mouse coordinates. Rendering is done via SVG elements, and the data consists of random x/y positions generated with `d3.range`.

AI-generated description

Example of zoom and drag in d3 v4.

This example has a modified drag function so that when you zoom in, you're still able to drag the circles to the correct mouse location. Here's an example of the drag problem.

forked from <a href='http://bl.ocks.org/puzzler10/'>puzzler10</a>'s block: <a href='http://bl.ocks.org/puzzler10/49f13307e818ea9a909ba5adba5b6ed9'>d3v4 - zoom and drag circles - drag adjusted for zoom </a>

forked from <a href='http://bl.ocks.org/Thanaporn-sk/'>Thanaporn-sk</a>'s block: <a href='http://bl.ocks.org/Thanaporn-sk/0e3e474cb6408266481992ae42b19ba1'>d3v4 - zoom and drag circles - drag adjusted for zoom </a>

Similar vizzes