如何在D3JS中创建跨越不同矩形的渐变?

时间:2017-03-30 17:25:16

标签: d3.js svg

在D3JS V4中:假设你有六个矩形。如何创建从第一个到最后一个流过的渐变?

Gradient across bars

我尝试为矩形创建一个组,然后将color-gradient-id添加到组中,但它仍然导致渐变在每个矩形内单独发生。

1 个答案:

答案 0 :(得分:3)

您必须将gradientUnits设置为userSpaceOnUse。根据文档,userSpaceOnUse

  

...表示坐标系中的值,这些值是在引用渐变元素时获取当前用户坐标系所得到的

这是一个没有userSpaceOnUse的演示,结果不是你想要的:



var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%");

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

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

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);

<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>
&#13;
&#13;
&#13;

现在有userSpaceOnUse的演示:

&#13;
&#13;
var svg = d3.select("svg");

var gradient = svg.append("defs")
  .append("linearGradient")
  .attr("id", "gradient")
  .attr("x1", "0%")
  .attr("y1", "50%")
  .attr("x2", "100%")
  .attr("y2", "50%")
  .attr("gradientUnits","userSpaceOnUse");

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

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

var g = svg.append("g")
  .style("fill", "url(#gradient)");

var rects = g.selectAll("foo")
  .data(d3.range(7))
  .enter()
  .append("rect")
  .attr("y", 20)
  .attr("x", (d, i) => 20 + 50 * i)
  .attr("width", 40)
  .attr("height", 40);
&#13;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>
&#13;
&#13;
&#13;