2017-11-18 166 views
3

我正在使用D3 v4並且似乎無法獲取多個項目以追加到節點。在下面的代碼中,我試圖讓文本與圖像一起出現,作爲我的力模擬的一部分。圖像和文字都需要在屏幕上一起移動。如果我只追加圖像或文本,但它無法將它們組合在一起,它完美地工作。當我運行它時,它只顯示角落中的1個節點。如何將多個項目附加到力仿真節點?

this.node = this.d3Graph.append("g") 
    .attr("class", "nodes") 
    .selectAll("circle") 
    .data(Nodes) 
    .enter() 
    .append("svg:image") 
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png') 
    .attr("height", 50) 
    .attr("width", 50) 
    .append("text") 
    .attr("x", 20) 
    .attr("y", 20) 
    .attr("fill", "black") 
    .text("test text"); 

this.force.on('tick', this.tickActions); 

tickActions() { 
    this.node 
     .attr("transform", function(d) { 
      return "translate(" + d.x + "," + d.y + ")"; 
     }) 

    this.force 
     .restart() 
} 

回答

2

不能追加<text>元素的<image>元素。您必須將<text>附加到<g>

最簡單的辦法是打破您的選擇:

this.node = this.d3Graph.selectAll(null) 
    .data(Nodes) 
    .enter() 
    .append("g") 
    .attr("class", "nodes"); 

this.node.append("svg:image") 
    .attr("xlink:href", 'https://seeklogo.com/images/T/twitter-2012-negative-logo-5C6C1F1521-seeklogo.com.png') 
    .attr("height", 50) 
    .attr("width", 50); 

this.node.append("text") 
    .attr("x", 20) 
    .attr("y", 20) 
    .attr("fill", "black") 
    .text("test text"); 

這裏我們使用數據來創建的輸入選擇<g>元素。然後,對每個<g>元素,我們附加一個<image>和一個<text>作爲孩子。

相關問題