如何将多个项目附加到力仿真节点?
问题描述:
我正在使用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()
}
答
不能追加<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>
作为孩子。