rveciana - color-scale-chooser

Color scale chooser

Open raw page in new tab

Small d3js function to build color scales.

<!DOCTYPE html>
<meta charset="utf-8">
<style>

</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="color-scale.js"></script>
<script>
//colors:["#c9d5a6", "#7fa67a", "#976a2f", "#79750a", "#7ab5e3", "#fefefe"]

var scaleValues = [{value: 0, color: "#c9d5a6"},
{value: 100, color: "#7fa67a"},

{value: 300, color: "#79750a"},
{value: 400, color: "#7ab5e3"},
{value: 500, color: "#fefefe"},
{value: 200, color: "#976a2f"}];

var squareWidth = 80, squareHeight = 30;


var svg = d3.select("body")
  .append("svg")
  .attr("width", 200)
  .attr("height", 400);

var scale = d3.ColorScaleChooser()
  .squareWidth(50)
  .scaleValues(scaleValues)
  .title("Altitude (m)")
  .on("change", function(d, min, max){
    var scaleWidth = 500;
    d3.select("#colorScale").remove();
    var canvasColorScale = d3.select("body").append("canvas")
      .attr("id", "colorScale")
      .attr("width", scaleWidth)
      .attr("height", 20);
    var contextColorScale = canvasColorScale.node().getContext("2d");
    var gradient = contextColorScale.createLinearGradient(0, 0, scaleWidth, 1);
    for (var i = 0; i < d.length; ++i) {
      gradient.addColorStop((d[i].value-min)/(max-min), d[i].color);
    }
    contextColorScale.fillStyle = gradient;
    contextColorScale.fillRect(0, 0, scaleWidth, 20);
  });

svg.call(scale);

</script>