D3.js: Switching colors in linear SVG gradient?

As the name says: with D3.js, is it possible to translate the color 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)"); 

Can I then move it to become a gradient going from blue to red, and not from yellow to red?

+7
source share
1 answer

Yes - changing the definition of the gradient is no different from changing the position of a circle or something similar with respect to D3. You could do what you want, for example, with the following code.

 gradient.select("stop") .transition() .attr("stop-color", "blue"); 
+6
source

All Articles