Skip to content

Instantly share code, notes, and snippets.

@mbostock

mbostock/.block Secret

Created May 11, 2016 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbostock/c0f75ad39c823902289916612933b3df to your computer and use it in GitHub Desktop.
Save mbostock/c0f75ad39c823902289916612933b3df to your computer and use it in GitHub Desktop.
Circle Dragging Ib
license: gpl-3.0

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.)

<!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