2015-02-23 81 views
0

我試圖更改每個path,以便它們從每個矩形的右側開始並連接到左側。目前,它們似乎穿過矩形,並在矩形內的某個位置具有起點/終點,而不是補償rect的大小。將鏈接附加到D3樹佈局中矩形的一側

我試圖操縱這個代碼:

 var diagonal = d3.svg.diagonal() 
     .source(function (d) { return { "x": d.source.y, "y": d.source.x }; }) 
     .target(function (d) { return { "x": d.target.y - 10, "y": d.target.x }; }) 
     .projection(function (d) { return [d.y + 0, d.x + 0]; 
     }); 

但只是在災難告終,但我相信,答案就在那邊的某個地方。

這是腳本的JSFiddle,因爲它代表着http://jsfiddle.net/ra26wnbb/

UPDATE 我觀看了D3 tree square node not in desired position,但我不知道它會與我的文字環繞工作。

+0

也許我做錯了什麼,而是你的小提琴不顯示任何內容。 – jmpyle771 2015-02-23 23:39:49

+0

使用谷歌鉻可能? – 2015-02-23 23:47:24

+0

@ barnacle.m你能告訴我,你究竟想要展示什麼,我沒有在D3樹佈局中追加鏈接到矩形的一邊,這裏鏈接是什麼意思? 而你的代碼工作正常。 – 2015-02-24 04:48:38

回答

2

首先,在wrap()裏面的工作完成後,您需要將結果高度存儲在文本的基準面上:d.height = 19 * (lineNumber + 1);。這樣,高度就可以滿足任何需求。例如,您可以使用它來設置wrap()之外的rect高度,而不是parentNode.children[0]之間的高度,這可以更好地分離關注點。無論如何,這是什麼wrap()結束是:

function wrap(text, width) { 
     text.each(function (d) { // DIFF add param d 
      var text = d3.select(this), 
       // DIFF: use datum to get name, instead of element text 
       words = d.name.split(/\s+/).reverse(), 
       word, 
       line = [], 
       lineNumber = 0, 
       lineHeight = 1.1, // ems 
       y = text.attr("y"), 
       dy = parseFloat(text.attr("dy")), 
       tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em"); 
      while (word = words.pop()) { 
       line.push(word); 
       tspan.text(line.join(" ")); 
       if (tspan.node().getComputedTextLength() > width) { 
        line.pop(); 
        tspan.text(line.join(" ")); 
        line = [word]; 
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); 
       } 
      } 

      // DIFF: store the height via the datum, d 
      d.height = 19 * (lineNumber + 1); 
      d3.select(this.parentNode.children[0]).attr('height', 19 * (lineNumber + 1)); 

     }); 
    } 
}); 

現在,你有d.height,你可以用它來計算對角線的端點的必要補償。

// calculate source and target offsets 
    // d.height gets set by the wrap() function 
    var diagonal = d3.svg.diagonal() 
     .source(function (d) { 
      return { 
       "x": d.source.x + d.source.height/2, 
       "y": d.source.y + 150 
      }; 
     }) 
     .target(function (d) { 
      return { 
       "x": d.target.x + d.target.height/2, 
       "y": d.target.y 
      }; 
     }) 
     .projection(function (d) { return [d.y + 0, d.x + 0]; 
     }); 

modified fiddle

+1

這是輝煌的謝謝。我不認爲我自己會想到這一點。 – 2015-02-24 10:13:51

+0

你能解釋如何在D3版本4中實現同樣的功能嗎? – Abhi 2017-03-07 17:36:57