Center force directed layout after tick using root node (return to center)

前端 未结 2 619
遥遥无期
遥遥无期 2021-01-05 18:27

I am experimenting with force directed layout using D3.js. What I need is center the layout by root (or other selected node) and return this node to the svg (e.g. canvas) ce

2条回答
  •  既然无缘
    2021-01-05 19:12

    Actually I solved this like this(similar to previous but more sophisticated):

    force.on("tick", function(e) {
    
         node.attr("transform", function(d) { 
             //TODO move these constants to the header section
            //center the center (root) node when graph is cooling down
            if(d.index==0){
                damper = 0.1;
                d.x = d.x + (w/2 - d.x) * (damper + 0.71) * e.alpha;
                d.y = d.y + (h/2 - d.y) * (damper + 0.71) * e.alpha;
            }
            //start is initiated when importing nodes from XML
            if(d.start === true){
                d.x = w/2;
                d.y = h/2;
                d.start = false;
            }
    
            r = d.name.length;
            //these setting are used for bounding box, see [http://blockses.appspot.com/1129492][1]
            d.x = Math.max(r, Math.min(w - r, d.x));
            d.y = Math.max(r, Math.min(h - r, d.y));
    
                return "translate("+d.x+","+d.y+")";            
    
         }
        );
    
         });   
    

提交回复
热议问题