1

我正在尝试将color = d3.scale.category10();var 中的颜色应用于圆形 svg 的渐变,我做错了什么?我所看到的只是color = d3.scale.category10();(蓝色)到 0% 不透明度渐变的第一种颜色,但仅此而已。如果我取出渐变,那么我会看到我想要的范围是 1-4?提前致谢!

var nodes = d3.range(300).map(function() { return {radius: Math.random() * 12 + 4}; }),
    root = nodes[0],
    color = d3.scale.category10();

root.radius = 0;
root.fixed = true;

var force = d3.layout.force()
  .gravity(0.05)
  .charge(function(d, i) { return i ? 0 : -4000; })
  .nodes(nodes)
  .size([width, height]);

  force.start();

var svg = d3.select("body").append("svg:svg")
  .attr("width", width)
  .attr("height", height);

var gradient = svg.append("defs").append("radialGradient")
  .attr("id", "gradient")
  .attr("cx", "50%")
  .attr("cy", "50%");

gradient.append("stop")
  .attr("offset", "75%")
  .style("stop-color", function(d, i) { return color(i % 4); })
  .attr("stop-opacity", "1");

gradient.append("stop")
  .attr("offset", "100%")
  .style("stop-color", function(d, i) { return color(i % 4); })
  .attr("stop-opacity", ".1");

svg.selectAll("circle")
  .data(nodes.slice(1))
  .enter().append("circle")
  .attr("r", function(d) { return d.radius; })
  .style("fill", "url(#gradient)");
4

1 回答 1

3

您的stop元素没有与它们连接的任何数据,因此在您的function (d, i),i中将始终为0. 如果你只想要两站,你可以这样做:

gradient.append("stop")
  .attr("offset", "75%")
  .style("stop-color", color(0))
  .attr("stop-opacity", "1");

gradient.append("stop")
  .attr("offset", "100%")
  .style("stop-color", color(1))
  .attr("stop-opacity", ".1");

相反,如果您只是想淡化圆圈的边缘,那么渐变根本不是您想要的。相反,您需要对每个圆圈应用纯色,然后在蒙版内创建一个仅不透明度的渐变,并将该蒙版应用于每个圆圈。像这样的东西:

var defs = svg.append('defs');
var gradient = defs.append('radialGradient')
    .attr('id', 'fadient');
gradient.append('stop')
    .attr('offset', '75%')
    .attr('stop-color', 'white')
    .attr('stop-opacity', 1)
gradient.append('stop')
    .attr('offset', '100%')
    .attr('stop-color', 'white')
    .attr('stop-opacity', .1)

var mask = defs.append('mask')
    .attr('id', 'mask')
    .attr('maskContentUnits', 'objectBoundingBox')
  .append('circle')
    .attr('fill', 'url(#fadient)')
    .attr('cx', .5)
    .attr('cy', .5)
    .attr('r', .5)

svg.selectAll("circle")
  .data(nodes.slice(1))
  .enter().append("circle")
  .attr('cx', function (d, i) { return 20 * i })
  .attr('cy', 50)
  .attr("r", function(d) { return d.radius; })
  .attr('mask', 'url(#mask)')
  .attr("fill", function (d, i) { return color(i); });
于 2013-02-06T08:28:03.667 回答