d3js力导向图动态添加每个节点的图像或圆形

3

我是D3JS的新手,我需要创建带有图像或圆形节点的力导向图。这意味着一个图像节点或圆形节点需要动态添加。这是否可能?如果有任何示例,请回答。

2个回答

7

如果你只想在圆形中间放置一张图片,请尝试以下方法:

/* Create nodes */
var node = vis.selectAll("g.node")
    .data(json.nodes) // get the data how you want
    .enter().append("svg:g")
    .call(node_drag);

/* append circle to node */
node.append("svg:circle")
    .attr("cursor","pointer")
    .style("fill","#c6dbef")
    .attr("r", "10px"})

/* append image to node */
node.append("image")
    .attr("xlink:href", "https://github.com/favicon.ico")
    .attr("x", -8)
    .attr("y", -8)
    .attr("width", 16)
    .attr("height", 16);

你可以添加标题、一些文本... 有关更多信息,请参见selection.append(name)的文档。

谢谢Chris James。是否可以有带文本的圆形和带图像的圆形? - user1159833
完全正确,它只是简单相加。了解如何操作的最佳方法是浏览www.d3js.org上力导向图的示例。 - Christopher Chiche

0

对于动态图像,您可以将图像保存在本地,并使用图像名称从本地使用动态图像。

要制作圆形,您可以使用:

 var groups = node.enter().append("g")
        .attr("class", "node")
        .attr("id", function (d) {
            return d.entityType;
        })
        .on('click', click)

    groups.append("circle")
       .attr("cursor", "pointer")
       .style("fill", function(d) { return color(d.entityType); })
       .style("fill", "#fff")
       .style("stroke-width", "0")
       .style("stroke", "#ddd")
     .attr("r", 20);

在这里,d.entityType 将是图像的名称示例: favicon.png
groups.append("image")
       .attr("xlink:href",function (d) {
            return "../assets/images/"+d.entityType+".png";
            })
        .attr("x", -14)
        .attr("y", -15)
        .attr("width", 30)
        .attr("height", 30)

如果你想在圆圈内添加文本,可以使用:

groups.append("text")
        .attr("dy", 18)
        .style("font-size", "2.5px")
        .style("text-anchor", "middle")
        .style('fill','#000')
        .attr("refX", 15)
        .attr("refY", -1.5)
        .text(function (d) {
            return d.entityName;
        });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接