d3: Optionally add child elements based on node content in force layout

走远了吗. 提交于 2019-12-12 21:06:21

问题


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

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?


回答1:


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


来源:https://stackoverflow.com/questions/12787769/d3-optionally-add-child-elements-based-on-node-content-in-force-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!