Line chart with Gradient - CanvasJS JavaScript Charts

Line chart with Gradient - CanvasJS JavaScript Charts

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

JavaScript

var chart = new CanvasJS.Chart("chartContainer", {   
  title: {
    text: "Line chart with Gradient"
  },
  data: [
    {
      type: "line",
      dataPoints: [
        { x: 1, y: 71, colour: -3 },
        { x: 2, y: 55, colour: 1 },
        { x: 3, y: 47, colour: 4},
        { x: 4, y: 99, colour: -5},
        { x: 5, y: 11, colour: 5}
      ]
    }					
  ]
});

setColour(chart);
chart.render();

function getColour(colour) {
	/* number of int values between -5 to 5 is 11
	 so colour value range (-5 to 5), is scaled to range 0 to 11.
   val = (colour - minIpVal) * (maxOpVal - minOpVal) / (maxIpVal - minIpVal) + minOpVal;
  */
  var val = ( colour - (-5) ) * ( 11 - 0 ) / ( 5 - (-5) ) + 0,
      r = Math.floor(255 - (23.13 * val)),
      g = Math.floor(23.13 * val);
  return "rgb(" + r + "," + g + ",0)";  
}

function setColour(chart) {
  for(var i = 0; i < chart.options.data.length; i++){
    for(var j = 0; j < chart.options.data[i].dataPoints.length; j++) {
      var dps = chart.options.data[i].dataPoints[j];
      dps.markerColor = getColour(dps.colour);
      dps.lineColor = getColour(dps.colour);
    }
  }
}