d3:可选地在强制布局中基于节点内容添加子元素 [英] d3: Optionally add child elements based on node content in force layout
问题描述
使用d3中的强制布局,我可以高兴地添加节点,例如,一个圆的SVG组和一些文本:
Using the force layout in d3, I can happily add nodes as, say, an SVG group of a circle and some text:
var node = vis.selectAll(".node")
.data(nodes)
.enter().append("svg:g")
.attr("class", "node");
node.append("svg:circle")
.attr("r", 5);
node.append("svg:text")
.text(function(d) { return d.nodetext });
但是,我想 依赖于节点数据:因此如果该节点的数据包含image属性,我想添加一个新的子元素(svg:image)。很容易将svg:image添加到所有节点(我只是像上面的圆和文本一样做)。还可以轻松地动态更改已创建的元素的属性(通过将函数作为属性的值,如上面的 text
)。我不知道如何添加 svg:image
子元素仅当数据包含图像
属性。
However, I would like to optionally add another element to the group, dependent on the node data: so if the data for this node contains an "image" attribute, I'd like to add a new child-element (an svg:image). It's easy to add the svg:image to all nodes (I just do it as I've done the circle and text above). It's also easy to dynamically change an attribute of an element you've already created (by having a function as the attribute's value, as per text
above). I do not know how to add an svg:image
child element only if the data contains an image
attribute. What's the best way of achieving this?
推荐答案
尝试 selection.filter :
node.filter(function(d) { return d.image; }).append("image")
.attr("xlink:href", function(d) { return d.image; })
.attr("width", 16)
.attr("height", 16);
这篇关于d3:可选地在强制布局中基于节点内容添加子元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!