<def> jam

Meant to be used with d3. Source code on Gist. Interactive Notebook.

Usage

svgGradientDefs(color_array [, gradient_id])

Examples

svgGradientDefs(["steelblue", "green"], "myGradient");

Ie. Generate a gradient from steelblue to green, call it myGradient.

<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:

How about svgGradientDefs(["white", "pink", "hotpink", "deeppink", "mediumvioletred"], "pinkish")?

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)

That's all!