Skip to main content
100%

Drag & Zoom

✓ Published0🌍 Public
Mmbostock
Last edited Jul 4, 2016
Created on May 31, 2016

This example combines `d3.drag` and `d3.zoom` on a Canvas to allow both panning the view and moving individual points. Clicking and dragging on the background pans the zoomable world, while dragging on a circle moves that circle in world coordinates. The code explicitly converts between pointer coordinates and world coordinates using the zoom transform’s `invertX`/`invertY` and `applyX`/`applyY` methods. It renders 2,000 points generated by a phyllotaxis pattern, drawn as a single Canvas path with `arc` calls.

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.

gpl-3.0 Licensed

Similar vizzes