【问题标题】:Gradient colors from d3.scale.category10() with opacity change on a svg circle?来自 d3.scale.category10() 的渐变颜色在 svg 圆上具有不透明度变化?
【发布时间】:2023-04-09 02:55:02
【问题描述】:

我正在尝试将 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)");

【问题讨论】:

  • category10 中的四种颜色映射到 300 个节点的集合,每个节点有 75 个。每个节点将只有一种颜色,整个集合的不透明度从 1 变为 0.1。

标签: svg d3.js gradient radial-gradients


【解决方案1】:

您的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");

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 2011-12-05
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多