Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3 physical gravity

I'm trying to design a simulation of physical gravity with the D3 library, but I'm not having a lot of luck. The 'layout' API reference states that physical gravity can be implemented through a positive 'charge' parameter, but I'm unsure of how this would work.

What I'm attempting to implement at the moment is a single SVG element that contains multiple variably-weighted and -sized rects rising at different speeds eventually going out of the viewport -- their weights will define the velocity at which they rise. (Basically, I'm just trying to implement a global gravitational pull from beyond the top of the viewport.)

Is there a feasible way of doing this in accordance with the D3 force layout? I'm just looking for conceptual solutions, but examples and code snippets are appreciated as well.

Thanks in advance!

like image 694
stephenkao Avatar asked Sep 24 '12 20:09

stephenkao


1 Answers

Here is couple ideas:

  1. You can directly modify vertical position of node in tick event handler:

    force.on("tick", function(e) {
        nodes.forEach(function(o, i) {
            o.y -= o.weight / 30;
         });
    
         node.attr("cx", function(d) { return d.x; })
             .attr("cy", function(d) { return d.y; });
    });
    

    You need to set force.gavity(0) for this approach.

  2. Or you can use force.gravity: it pulls nodes towards layout center, you can specify svg transfromation to shift layout center above viewport
like image 62
Ivan Solntsev Avatar answered Sep 23 '22 22:09

Ivan Solntsev