Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop moving other nodes while dragging one node in D3 forceSimulation

I made a D3 forced-directed graph by d3.forceSimulation() and attached the drag function. While clicking one node, I don't want other nodes to move accordingly. Now I can freeze the node being dragged by setting the d.fx and d.fy as the following:

function dragended(d) {
    if (!d3.event.active) simulation.alphaTarget(0);
    d.fx = d.x;
    d.fy = d.y;
}

Is it possible to freeze all the other nodes while dragging one node?

like image 303
user19881219 Avatar asked Apr 28 '26 13:04

user19881219


1 Answers

Thanks @rioV8 for the hint! I tried to fix the other nodes while dragging one node.

node.call(d3.drag()
    .on('start', dragstarted)
    .on('drag', dragged)
    .on('end', dragended))

function dragged(d) {
    d.fx = d3.event.x;
    d.fy = d3.event.y;
    fix_nodes(d);
}

// Preventing other nodes from moving while dragging one node
function fix_nodes(this_node) {
    node.each(function(d){
        if (this_node != d){
            d.fx = d.x;
            d.fy = d.y;
        }
    });
}

Demo is here: https://jsfiddle.net/casbie/21dvjcgn/

like image 68
user19881219 Avatar answered May 01 '26 15:05

user19881219



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!