Setting different images for D3 force-directed layout nodes

扶醉桌前 提交于 2019-12-04 09:56:05

This is a jsfiddle that is exuivalent to the first example that you linked. I juist changed getting data to be from the JavaScript code instead of json file, since jsfiddle doesn't support external json files that well.


First Solution

Now, let's replace constant image with set of different images

Instead of this code:

.attr("xlink:href", "https://github.com/favicon.ico")

we'll insert this code:

.attr("xlink:href", function(d) {
    var rnd = Math.floor(Math.random() * 64 + 1);
    var imagePath =
           "http://www.bigbiz.com/bigbiz/icons/ultimate/Comic/Comic"
           + rnd.toString() + ".gif";
    console.Log(imagePath);
    return imagePath;
})

and we'll get this:


Second Solution

As you suggested in your code from the question, one could use built-in SVG symbols.

Instead of this whole segment for inserting images:

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

we could use this code:

node.append("path")
    .attr("d", d3.svg.symbol()
    .size(function(d) {
        return 100;
    })
    .type(function(d) {
        return d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)];
    }))
    .style("fill", "steelblue")
    .style("stroke", "white")
    .style("stroke-width", "1.5px")
    .call(force.drag);

and we'll get this:


Hope this helps.

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