如何根据 D3.js 中的数据附加不同的形状,包括图像?

How to append different shapes including images depending on data in D3.js?

我试图通过查找几个类似的问题来解决这个问题,但 none 可以解决它。我想使用 JSON-File:

中的这种形式的数据创建一个力导向图
{
"nodes":[
    {"name":"A", "imagelink": "url-to-img" ,"shape-type":circle},
    {"name":"B", "imagelink": "url-to-img" , "shape-type":rectangle},
    {"name":"A", "imagelink": "url-to-img" ,"shape-type":triangle}
 ]
"links":[
    {"source":1,"target":0,"value":1},
    {"source":2,"target":1,"value":1},
    {"source":2,"target":0,"value":1}
 ]
}

图形的节点应该是一组由几何形状(由 "shape-type" 定义)和图像(由 "imagelink" 定义)组成的组。

这是我使用的基本强制布局代码:

var width = 960,
    height = 500;

var force = d3.layout.force()
        .charge(-1000)
        .linkDistance(150)
        .size([width, height]);

var svg = d3.select("body").append("svg");

d3.json("json-file.json");

force
     .nodes(graph.nodes)
     .links(graph.links)
     .start();

var link = svg.selectAll(".link")
            .data(graph.links)
            .enter().append("line")
            .attr("class", "link")
            .style("stroke-width", function (d) {
                return Math.sqrt(d.value);
            });

var node = svg.selectAll(".node")
            .data(graph.nodes)
            .enter().append("g")                
            .attr("class", "node")
            .call(force.drag);

为了将图像包含到形状中,我使用了 "clip-path method"(圆形示例):

node.append("circle")
            .attr("r", 20)
            .attr("cy", 0)
            .attr("cx", 0)
            .style("fill", "white")
            .style("stroke", "black")
            .style("stroke-width", "2"); 

 var clippath = node.append('clipPath').attr(function (d) {
            return ("clip-" + convert_shape(d.group))
        });

 clippath.append("circle")
            .attr("r", 19)
            .attr("cy", 0)
            .attr("cx", 0);

 node.append("image")
            .attr("x", -37.5)
            .attr("y", -37.5)
            .attr("height", 75)
            .attr("width", 75)
            .attr("xlink:href", function (d) {return (d.imagelink)})
            .attr("clip-path", function (d) {return ("url(#clip-" + d.shapetype) + ")")
            });

如您所见,我的问题是使 append() 函数依赖于数据。那么我该如何实现呢?

谢谢。

Here 是一个工作 fiddle 用于绘制具有不同形状和图像的力导向图。

我使用图案解决方案将图像包含到形状中。