为D3力导向的布局节点设置不同的图像 [英] Setting different images for D3 force-directed layout nodes
问题描述
我一直在尝试制作特定类型的力直接图表,类似于此(是一个jsfiddle,是相当于你链接的第一个例子。我juist更改获取数据从因为jsfiddle不支持外部json文件。
第一个解决方案 h2>
现在,让我们用一组不同的图片替换常量图片
而不是这个代码:
.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;
})
,我们会得到:
希望这有助。
I've been trying to make a specific type of force direct graph, similar to this (http://bl.ocks.org/mbostock/950642):
However, instead of having all the same images I wish to have different images representing different information on the graph.
My first step to this is being able to change all the circle images to random linked shapes. Whatever I try to implement in my code, the circles I have just disappear, instead of being replaced by different shapes. Any help on this problem would be great. Here is the code. Sorry, I'm also new to this site.
// 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 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.
这篇关于为D3力导向的布局节点设置不同的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!