8

Just as the title says: with D3.js, is it possible to transition the colour of a linear gradient?

For example, if I have this gradient:

var gradient = svg.append("svg:defs")
  .append("svg:linearGradient")
    .attr("id", "gradient")
    .attr("x1", "0%")
    .attr("y1", "0%")
    .attr("x2", "100%")
    .attr("y2", "0%")
    .attr("spreadMethod", "pad");
gradient.append("svg:stop")
    .attr("offset", "0%")
    .attr("stop-color", "yellow")
    .attr("stop-opacity", 0.6);
gradient.append("svg:stop")
    .attr("offset", "100%")
    .attr("stop-color", "red")
    .attr("stop-opacity", 0.6);
svg.append("svg:rect")
    .attr("width", width)
    .attr("height", 8)
    .style("fill", "url(#gradient)");

Could I then transition it to become a gradient going from blue to red, rather than yellow to red?

4

1 回答 1

7

是的——就 D3 而言,更改渐变的定义与更改圆的位置或类似的东西没有什么不同。例如,您可以使用以下代码执行您想要的操作。

gradient.select("stop")
        .transition()
        .attr("stop-color", "blue");
于 2013-06-15T18:15:18.790 回答