答案 0 :(得分:4)
Here is jsfiddle解决方案。它基于SVG radial gradients。
对于每个节点,定义一个渐变:
var grads = svg.append("defs").selectAll("radialGradient")
.data(nodes)
.enter()
.append("radialGradient")
.attr("gradientUnits", "objectBoundingBox")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", "100%")
.attr("id", function(d, i) { return "grad" + i; });
grads.append("stop")
.attr("offset", "0%")
.style("stop-color", "white");
grads.append("stop")
.attr("offset", "100%")
.style("stop-color", function(d) { return color(d.cluster); });
然后,而不是行:
.style("fill", function(d) { return color(d.cluster); })
此行添加在创建圈子的代码中:
.attr("fill", function(d, i) {
return "url(#grad" + i + ")";
})
这会产生这样的效果:(我使用的动画gif对颜色数量有一些限制,因此渐变不像实际例子那样平滑)
答案 1 :(得分:2)
根据您的要求使用不同的颜色创建线性或径向渐变。将填充属性设置为渐变。
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#0c0")
.attr("stop-opacity", 1);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#c00")
.attr("stop-opacity", 1);
var node = svg.selectAll("circle")
.data(nodes)
.enter().append("circle")
.style("fill", "url(#gradient)")
.call(force.drag);