Skip to content

Instantly share code, notes, and snippets.

@luciyer
Created November 5, 2020 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luciyer/0e406383a91d408203f6fc7ef407beb2 to your computer and use it in GitHub Desktop.
Save luciyer/0e406383a91d408203f6fc7ef407beb2 to your computer and use it in GitHub Desktop.
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