D3力布局 - 如何实现节点的3D外观?

时间:2014-07-10 09:59:51

标签: javascript svg d3.js 3d force-layout

以下是D3群集力布局的jsfiddle

enter image description here

如何实现类似于此图片的节点的3D外观:(不要注意图表本身,这只是圆圈“外观”的插图)

enter image description here

2 个答案:

答案 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对颜色数量有一些限制,因此渐变不像实际例子那样平滑)

enter image description here

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