Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript function to generate SVG gradient <defs> object
/*
Dependent on d3.js.
*/
const svgGradientDefs = (color_array, gradient_id) => {
if (color_array.length < 2)
throw new Error("Argument should be array of two or more colors.")
var pctStep = 100 / (color_array.length - 1),
stops = color_array.map((d, i) => ({ offset: i * pctStep, color: d }));
const gradient = d3.create("svg"),
defs = gradient.append("defs");
defs.append("linearGradient")
.attr("id", gradient_id ? gradient_id : "gradient")
.selectAll("stop")
.data(stops)
.enter()
.append('stop')
.attr("offset", d => d.offset + '%')
.attr("stop-color", d => d.color);
return gradient.node();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment