<def> jam

Using d3 and vanilla javascript to generate <svg><defs> . Click the image below for usage and to test it yourself.


Source

const svgGradientDefs = (color_array, gradient_id) => {
  
  if (color_array.length < 2)
    return '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();
  
}

Recent

Categories