我一直在尝试制作一种特定类型的力有向图,类似于此(http://bl.ocks.org/mbostock/950642):
但是,我希望不同的图像代表图表上的不同信息,而不是所有相同的图像。
我的第一步是能够将所有圆形图像更改为随机链接的形状。无论我尝试在我的代码中实现什么,我的圆圈都消失了,而不是被不同的形状所取代。对这个问题的任何帮助都会很棒。这是代码。对不起,我也是这个网站的新手。
// nodes
var nodeSelecton = svg.selectAll(".node").data(nodes).enter().append("g").attr({
class : "node"
}).call(force.drag);
nodeSelecton.append("circle").attr({
r : nodeRadius
}).style("fill", function(d) {
return color(d.group);
});
nodeSelecton.append("svg:text").attr("text-anchor", "middle").attr('dy', ".35em").text(function(d) {
return d.name;
});
// Add a new random shape.
// nodes.push({
// type: d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)],
// size: Math.random() * 300 + 100
最佳答案
This是一个 jsfiddle,相当于您链接的第一个示例。我只是将获取数据更改为来自 JavaScript 代码而不是 json 文件,因为 jsfiddle 不太支持外部 json 文件。
第一个解决方案
现在,让我们用一组不同的图像替换常量图像
代替这段代码:
.attr("xlink:href", "https://github.com/favicon.ico")
我们将插入这段代码:
.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;
})
我们会得到 this :
第二种解决方案
正如您在问题代码中所建议的那样,可以使用内置的 SVG 符号。
而不是插入图像的整个片段:
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", -8)
.attr("y", -8)
.attr("width", 16)
.attr("height", 16);
我们可以使用这段代码:
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);
我们会得到 this :
希望这对您有所帮助。
关于javascript - 为 D3 力导向布局节点设置不同的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18178008/