Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active July 5, 2019 15:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save mbostock/22994cc97fefaeede0d861e6815a847e to your computer and use it in GitHub Desktop.
Save mbostock/22994cc97fefaeede0d861e6815a847e to your computer and use it in GitHub Desktop.
Circle Dragging I
license: gpl-3.0
redirect: https://observablehq.com/@d3/circle-dragging-i

This example demonstrates applying d3.drag for dragging circles in SVG. Each circle’s datum is an object with x and y properties. The data and the circle element’s position are updated during the drag event. The circle is raised to the foreground at the start of a drag, and a temporary stroke is applied during drag for visual feedback.

Compare this to dragging Canvas circles. Selection can be improved using a Voronoi overlay.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.active {
stroke: #000;
stroke-width: 2px;
}
</style>
<svg width="960" height="500"></svg>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
radius = 32;
var circles = d3.range(20).map(function() {
return {
x: Math.round(Math.random() * (width - radius * 2) + radius),
y: Math.round(Math.random() * (height - radius * 2) + radius)
};
});
var color = d3.scaleOrdinal()
.range(d3.schemeCategory20);
svg.selectAll("circle")
.data(circles)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", radius)
.style("fill", function(d, i) { return color(i); })
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function dragstarted(d) {
d3.select(this).raise().classed("active", true);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function dragended(d) {
d3.select(this).classed("active", false);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment