Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3.js: Transition the colours in an SVG linear gradient?

Tags:

svg

d3.js

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?

like image 908
Richard Avatar asked Jun 15 '13 18:06

Richard


1 Answers

Yes -- changing the definition of a gradient is no different to changing the position of a circle or something like that as far as D3 is concerned. You could do what you want for example with the following code.

gradient.select("stop")
        .transition()
        .attr("stop-color", "blue");
like image 189
Lars Kotthoff Avatar answered Nov 08 '22 22:11

Lars Kotthoff