2012-02-20 36 views
5

我正在試驗使用D3.js的強制佈局佈局。我需要的是在根節點(或其他選定的節點)的中心佈局,並在滴答功能完成(圖形alpha爲低)後將此節點返回到svg(例如畫布)中心。可能嗎?我發現了一個例子在使用根節點勾選中心力指向佈局(返回中心)

http://bl.ocks.org/1080941

但我無法使根(使用APLHA或其他自定義蜱函數計算時)回返回到中心(中心的佈局由該特定節點)。

任何幫助,將不勝感激。

回答

6

其實我解決了這個這樣的(類似於以前的但更復雜):

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+")";    

    } 
    ); 

    }); 
2

嘗試改變力的事件處理程序是這樣的:

force.on("tick", function(e) { 
nodes[0].x = w/2; 
nodes[0].y = h/2; 

var k = 0.05 * e.alpha; 
      nodes.forEach(function(o, i) { 
      o.y += (nodes[0].y - o.y) * k; 
      o.x += (nodes[0].x - o.x) * k; 
      }); 

link.attr("x1", function(d) { return d.source.x; }) 
    .attr("y1", function(d) { return d.source.y; }) 
    .attr("x2", function(d) { return d.target.x; }) 
    .attr("y2", function(d) { return d.target.y; }); 

node.attr("cx", function(d) { return d.x; }) 
    .attr("cy", function(d) { return d.y; }); 
}); 
+0

感謝您的答覆。我已經在使用這個解決方案,問題是所選擇的節點是可拖動的,但在圖形解決後它不會返回給定的(原始)座標。我也嘗試使用圖形滴答功能的alpha(熱)值,但都沒有解決方案的工作。我需要允許用戶拖動圖形,然後通過某些選定節點將圖形返回到「固定」位置:-) – Bery 2012-02-22 13:56:23