# \<def\> jam Meant to be used with d3. [Source code on Gist](https://gist.github.com/luciyer/0e406383a91d408203f6fc7ef407beb2). [Interactive Notebook](https://observablehq.com/@luciyer/svg-gradients-chrome-safari). ## usage `svgGradientDefs(color_array [, gradient_id])` ## examples `svgGradientDefs(["steelblue", "green"], "myGradient");` Ie. Generate a gradient from steelblue to green, call it `myGradient`. ```text <svg> <defs> <linearGradient id="myGradient"> <stop offset="0%" stop-color="steelblue"></stop> <stop offset="100%" stop-color="green"></stop> </linearGradient> </defs> </svg> ``` Which can now be applied to some element ie. ``` // Create SVG const svg = d3.create("svg") .attr("width", width) .attr("height", 100); // Append generated <defs> svg .node() .appendChild(svgGradientDefs(["steelblue", "green"], "watery")); // Append <rect> and set fill to gradient svg .append("rect") .attr("width", width) .attr("height", 100) .attr("fill", "url(#watery)") return svg.node(); ``` That "watery" rect would look like this: ![[media/dj1.svg]] How about `svgGradientDefs(["white", "pink", "hotpink", "deeppink", "mediumvioletred"], "pinkish")`? ![[media/dj2.svg]] Ooh, nice. Definitely pinkish. Or to create a ramp, such as for the legend of a chart using one of d3's color scales? ``` const steps = d3.range(0, 15), color_array = steps.map((_,i) => d3.interpolateInferno(i / (steps.length - 1))); svgGradientDefs(color_array) ``` ![[media/dj3.svg]] That's all!