Skip to main content
100%

Drag & Zoom

✓ Published0🌍 Public
SServuc
Last edited Aug 16, 2016
Created on Aug 16, 2016

This example combines d3-drag and d3-zoom on a canvas to let users pan and zoom a field of 2,000 points arranged in a phyllotaxis spiral—a sunflower-like pattern. Dragging the background pans the view, while dragging an individual circle moves it in world coordinates. The code distinguishes between pointer coordinates and the zoomed coordinate space using d3.zoom’s transform inversion methods, then renders points via a single canvas path with `context.arc`.

AI-generated description

This example shows how to combine d3-drag and d3-zoom to allow dragging of individual circles within a zoomable canvas. If you click and drag on the background, the view pans; if you click and drag on a circle, it moves.

The tricky part of this example is the need to distinguish between two coordinate spaces: the world coordinates used to position the circles, and the pointer coordinates representing the mouse or touches. The drag behavior doesn’t know the view is being transformed by the zoom behavior, so you must convert between the two coordinate spaces.

Compare this to the simpler SVG implementation.

forked from <a href='http://bl.ocks.org/mbostock/'>mbostock</a>'s block: <a href='http://bl.ocks.org/mbostock/2b534b091d80a8de39219dd076b316cd'>Drag & Zoom</a>

gpl-3.0 Licensed

Similar vizzes