D3byEX 8.4: Drag and Drop (Adapted to D3.js v4)
<!DOCTYPE html>
<html>
<meta charset=utf-8>
<head>
<meta name="description" content="D3.js v4, drag circles" />
</head>
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
<script>
var width = 450, height = 450, radius = 50;
var svg = d3.select('body')
.append('svg')
.attrs({ 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.scaleOrdinal(d3.schemeCategory10);
var circles = svg.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attrs({r: radius, fill: colors,
transform: function (d) {
return 'translate(' + d + ')'
}
});
var dragBehavior = d3.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>