Skip to content

Instantly share code, notes, and snippets.

@ch-bu
Forked from mbostock/.block
Last active October 5, 2016 18:32
Show Gist options
  • Save ch-bu/2b879a56ee49aa487109abb18189034f to your computer and use it in GitHub Desktop.
Save ch-bu/2b879a56ee49aa487109abb18189034f to your computer and use it in GitHub Desktop.
Dragging with lines
license: gpl-3.0
height: 500

This is a simple dragging example adapted by the version of Mike Bostock

<!DOCTYPE html>
<head>
<title>Circle Dragging</title>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.active {
stroke: #000;
stroke-width: 2px;
}
</style>
</head>
<body>
<script>
// Init variables
var width = 960;
var height = 500;
var radius = 20;
var lineX1, lineY1;
// Create svg
var svg = d3.select('body').append('svg')
.attr('width', width)
.attr('height', height);
// Create array of multiple circles
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)
};
});
// Create 20 distinct colors
var color = d3.scaleOrdinal()
.range(d3.schemeCategory20);
// Add circles to svg
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));
/**
* Drag has started
* @return null
*/
function dragStarted(d) {
// Add active class to circle
d3.select(this).raise()
.classed('active', true);
// Save x and y coordinates
// where the dragging starts
lineX1 = d3.event.x;
lineY1 = d3.event.y;
}
/**
* Element is dragged
* @return null
*/
function dragged(d) {
// Follow the mouse with
// the chosen circle
d3.select(this)
.attr('cx', d.x = d3.event.x)
.attr('cy', d.y = d3.event.y);
}
/**
* Dragging stopped
* @return null
*/
function dragEnded(d) {
// Remove active class from circle
d3.select(this).classed('active', false);
// Append line that tracks
// the dragging movement
svg.append('line')
.style('stroke', 'black')
.attr('x1', lineX1)
.attr('y1', lineY1)
.attr('x2', d3.event.x)
.attr('y2', d3.event.y);
}
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment