2014-07-10 35 views

回答

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 + ")"; 
}) 

這產生這個eff ECT:(動畫GIF,我使用的具有用於顏色數量一定的侷限性,所以梯度不光滑如在真實的例子)

enter image description here

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);