Skip to content

Instantly share code, notes, and snippets.

@d3byex
Last active March 6, 2017 22:30
Show Gist options
  • Save d3byex/d303655effafc1f3e011 to your computer and use it in GitHub Desktop.
Save d3byex/d303655effafc1f3e011 to your computer and use it in GitHub Desktop.
D3byEX 8.4: Drag and Drop
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3byEX 8.4" />
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var width = 450, height = 450, radius = 50;
var svg = d3.select('body')
.append('svg')
.attr({
width: width,
height: height
});
var data = [
[width / 2 - radius, height / 2 - radius],
[width / 2 - radius, height / 2 + radius],
[width / 2 + radius, height / 2 - radius],
[width / 2 + radius, height / 2 + radius]];
var colors = d3.scale.category10();
var circles = svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr({
r: radius,
fill: colors,
transform: function (d) { return 'translate(' + d + ')' }
});
var dragBehavior = d3.behavior.drag()
.on('drag', onDrag);
circles.call(dragBehavior);
function onDrag(d) {
var x = d3.event.x,
y = d3.event.y;
if ((x >= radius) && (x <= width - radius) &&
(y >= radius) && (y <= height - radius)) {
d3.select(this)
.attr('transform', function () {
return 'translate(' + x + ', ' + y + ')';
});
}
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment