drag = circles => {
function dragsubject(event) {
let subject = null;
let distance = maxDistance;
for (const c of circles) {
let d = Math.hypot(event.x - c.x, event.y - c.y);
if (d < distance) {
distance = d;
subject = c;
}
}
return subject;
}
function dragstarted(event) {
event.subject.active = true;
}
function dragged(event) {
const pos = event.subject.proj(event.x, event.y, circles);
event.subject.x = pos.x;
event.subject.y = pos.y;
if(event.subject.mag != undefined) {
event.subject.m = event.subject.mag(pos.x, pos.y, circles);
}
if(event.subject.update != undefined) {
event.subject.update(pos.x, pos.y, circles);
}
for(const circle of circles) {
if(circle == event.subject.circle) continue;
if(circle.m != undefined && circle.proj_mag != undefined) {
circle.x = circle.proj_mag(circle.m, circles).x;
circle.y = circle.proj_mag(circle.m, circles).y;
}
}
}
function dragended(event) {
event.subject.active = false;
}
return d3.drag()
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}