2016-08-11 110 views
0

我想創建一個強制圖併爲每個節點插入foreignObject。D3節點選擇如何在D3力圖中起作用?

simulation 
      .nodes(graph.nodes) 
      .on("tick", ticked) 
      .on("end", graphended); 

     var node = svg.append("g") 
        .attr("class", "nodes") 
        .selectAll("circle") 
        .data(graph.nodes) 
        .enter().append("foreignObject") 
           .attr("width",img_w) 
           .attr("height",img_h) 
          .append("xhtml:body") 
          .html(function(d){ 
           return '<span class="custom-icon-container-circle">Some sample content</span>'; 
          }) 
          .call(d3.drag() 
            .on("start", dragstarted) 
            .on("drag", dragged) 
            .on("end", dragended)); 

和TICK功能我下面的方式來分配xy座標。

function ticked() { 
      node 
       .attr("x", function(d) { 
        var xPos = findPosX(d.x, img_w); 
        return xPos-img_w/2; 
       }) 
       .attr("y", function(d) { 
        var yPos = findPosY(d.y, img_h); 
        return yPos-img_h/2; 
       }); 
     } 

但是,在這種方法蜱,而不是給xy位置到foreignObject它被分配位置向foreignObject,其使得節點在實際座標不位置內body元件。

現在,代碼確實有效(如果我刪除foreignObject並放置另一個元素標籤並將位置賦予該元素),所以我認爲在我的選擇器和append語句中存在一個問題,因爲它創建了上面的foreignObject在元素的內部選擇。

回答

1

d3方法鏈返回,返回的東西,你的情況是這樣的.append("xhtml:body")的最後一件事,所以node持有到引用不給foreignObject。將您的代碼更改爲:

var node = svg.append("g") 
.attr("class", "nodes") 
.selectAll("circle") 
.data(graph.nodes) 
.enter().append("foreignObject") 
.attr("width",img_w) 
.attr("height",img_h); 

node.append("xhtml:body") 
    .html(function(d){ 
    return '<span class="custom-icon-container-circle">Some sample content</span>'; 
    }) 
    .call(d3.drag() 
    .on("start", dragstarted) 
    .on("drag", dragged) 
    .on("end", dragended));