Force directed graph: sticky nodes
Sticky nodes are where nodes are “stuck” once you’ve finished dragging them. They won’t move again once the mouse has been released - unless you drag them again, of course. Click on the image above for spoilers!
It’s super easy to make your nodes sticky.
Start with the example here.
Scroll down to the drag_end
function. It looks like
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
Currently it is telling the force directed graph to release the nodes when the mouse is released.
Change this to
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = d.x;
d.fy = d.y;
}
and the nodes will be “stuck” when you release the mouse cursor.
You can mess around with this if you’d like. For example changing this to
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = d.x;
d.fy = null;
}
locks the x-position of the nodes only, so that the nodes get a “yo-yo” effect. You can do a similar thing with the y-position.
Just for fun you could set them all to a constant value
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = 300;
d.fy = 200;
}
and watch chaos unfold as every node snaps back to the same place.
Or perhaps invert them
function drag_end(d) {
if (!d3.event.active) simulation.alphaTarget(0);
d.fx = d.y;
d.fy = d.x;
}
and laugh at the end user who puts up with your shit.
Hope you found that useful! Click here to view to the rest of the force directed graph series.