Skip to content

Instantly share code, notes, and snippets.

@puzzler10
Last active February 16, 2021 21:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save puzzler10/9159a992f58aa4277c2583fa41f01ed0 to your computer and use it in GitHub Desktop.
Save puzzler10/9159a992f58aa4277c2583fa41f01ed0 to your computer and use it in GitHub Desktop.
Dragging Circles

Example of using version 4 of d3.js to drag circles around the screen. Want to learn this? Read this.

<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//create some circles at random points on the screen
//create 50 circles of radius 20
//specify centre points randomly through the map function
radius = 20;
var circle_data = d3.range(50).map(function() {
return{
x : Math.round(Math.random() * (width - radius*2 ) + radius),
y : Math.round(Math.random() * (height - radius*2 ) + radius)
};
});
//add svg circles
var circles = d3.select("svg")
.append("g")
.attr("class", "circles")
.selectAll("circle")
.data(circle_data)
.enter()
.append("circle")
.attr("cx", function(d) {return(d.x)})
.attr("cy", function(d) {return(d.y)})
.attr("r", radius)
.attr("fill", "green");
//create drag handler with d3.drag()
//only interested in "drag" event listener, not "start" or "end"
var drag_handler = d3.drag()
.on("drag", function(d) {
d3.select(this)
.attr("cx", d.x = d3.event.x )
.attr("cy", d.y = d3.event.y );
});
//apply the drag_handler to our circles
drag_handler(circles);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment