2016-08-11 109 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));