chroma.js legend scale example

by John Doe

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/chroma-js/2.4.2/chroma.min.js"></script>
<div id="result"></div>

CSS

.gradient {
    width: 85%;
    white-space: nowrap;
    position: relative;
    display: inline-block;
    top: 4px;
    padding-bottom: 15px;
}

.gradient .domain-min {
    position: absolute;
    left: 0;
    font-size: 11px;
    bottom: 3px;
}
.gradient .domain-med {
    position: absolute;
    right: 25%;
    left: 25%;
    text-align: center;
    font-size: 11px;
    bottom: 3px;
}
.gradient .domain-max {
    position: absolute;
    right: 0;
    font-size: 11px;
    bottom: 3px;
}


.grad-step {
    display: inline-block;
    height: 20px;
    width: 1%;
}

JavaScript

function legendGenerator(d) {
  var s = '';
  var dom = d.domain ? d.domain() : [0,1],
      dmin = Math.min(dom[0], dom[dom.length-1]),
      dmax = Math.max(dom[dom.length-1], dom[0]);
  for (var i=0;i<=100;i++) {
    s += '<span class="grad-step" style="background-color:'+d(dmin + i/100 * (dmax - dmin))+'"></span>';
  }
  s += '<span class="domain-min">'+dmin+'</span>';
  s += '<span class="domain-med">'+((dmin + dmax)*0.5)+'</span>';
  s += '<span class="domain-max">'+dmax+'</span>';
  return '<div class="gradient">'+s+'</div>';
}

const tempScale = chroma.scale('Spectral').domain([1,0]);
const tempScale2 = chroma.scale(['#88bb2f', '#ff7b34', '#CC0000', '#79077B', '#000000']).domain([0,1]);
console.log(tempScale2.colors(20))
const res = document.getElementById('result');
res.innerHTML = `
  ${legendGenerator(tempScale)}
  ${legendGenerator(tempScale2)}
`;