Skip to main content
100%

Circle Dragging II

✓ Published0🌍 Public
Mmbostock
Last edited Jul 5, 2019
Created on May 11, 2016

This example shows a canvas-based visualization where users can drag any of twenty randomly positioned circles. It uses the d3.drag module with a custom subject function for hit-testing, checking if the pointer falls within a circle’s radius. During a drag, the circle is reordered to the foreground, marked with a temporary stroke, and its position updates, triggering a redraw via render listeners. The implementation relies on D3 v4’s event handling, Canvas’s 2D context, and d3.scaleOrdinal with the schemeCategory20 palette for circle fill colors, producing smooth, interactive feedback.

AI-generated description

This example demonstrates applying d3.drag for dragging circles in Canvas. A custom drag subject performs hit-testing to determine which circle to drag, if any. The circle’s position is updated during the drag event. The circle is raised to the foreground at the start of a drag by reordering the data, and a temporary stroke is applied during drag for visual feedback.

The render function is also registered as a listener to update the display after any drag event. The display will thus be redrawn once per active pointer, but since the number of active pointers is typically small (1, maybe 2), the cost is negligible.

The hit-testing here is simple: the topmost circle that contains the active pointer is returned. A better technique is to choose the closest circle to the active pointer, allowing accurate selection even if the pointer is outside the circle.

Compare this to dragging SVG circles.

gpl-3.0 Licensed

Similar vizzes