<def> jam

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


svgGradientDefs(color_array [, gradient_id])


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

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

    <linearGradient id="myGradient">
      <stop offset="0%" stop-color="steelblue"></stop>
      <stop offset="100%" stop-color="green"></stop>

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> 
    .appendChild(svgGradientDefs(["steelblue", "green"], "watery"));
  // Append <rect> and set fill to gradient
      .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)));


That's all!