Javascript function to generate SVG gradient <defs> object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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