This is a variant of circle dragging that applies the event listener to a group element rather than to the circle elements individually. This is a slight performance optimization, but in practice, there is very little reason to do this. (If you really need thousands of draggable circles, you’ll probably want to render them with Canvas, and you might want to consider different interaction techniques and visual forms.)
-
-
Save mbostock/c0f75ad39c823902289916612933b3df to your computer and use it in GitHub Desktop.
Circle Dragging Ib
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: gpl-3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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.0.0-alpha.37.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.scaleCategory20(); | |
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); }); | |
svg.call(d3.drag() | |
.subject(function() { return d3.event.sourceEvent.target.__data__; }) | |
.on("start", dragstarted)); | |
function dragstarted() { | |
var circle = d3.select(d3.event.sourceEvent.target) | |
.raise() | |
.classed("active", true); | |
d3.event | |
.on("drag", dragged) | |
.on("end", dragended); | |
function dragged() { | |
circle | |
.attr("cx", d3.event.subject.x = d3.event.x) | |
.attr("cy", d3.event.subject.y = d3.event.y); | |
} | |
function dragended() { | |
circle | |
.classed("active", false); | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment