【问题标题】:How does D3 node selection work in D3 force graph?D3 节点选择在 D3 力图中如何工作?
【发布时间】:2016-08-11 21:54:16
【问题描述】:

我正在尝试创建一个力图并为每个节点插入 foreignObject。

    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 函数中,我按照以下方式分配 x 和 y 坐标。

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;
                });
        }

但是在这个tick方法中,不是将x和y位置分配给foreignObject,而是将位置分配给foreignObject内部的body元素,这使得节点不在实际坐标处。

现在,代码确实可以工作(如果我删除 foreignObject 并放置另一个元素标记并且位置被赋予该元素),所以我认为在上面创建 foreignObject 的选择器和附加语句中存在问题,如它正在选择元素的内部。

【问题讨论】:

    标签: force-layout d3.js


    【解决方案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));
    

    【讨论】:

      猜你喜欢
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 1970-01-01
      • 2015-07-30
      • 2023-03-20
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多