Drawing Indexlabel Line in Line Chart - CanvasJS JavaScript Charts

Drawing Indexlabel Line in Line Chart - 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", {
	theme: "light2",
	title: {
  	text: "Drawing Index Label Line in Line Chart"
  },
  data: [
    {
      type: "line",
      indexLabelLineLength: 20,
      indexLabelFontSize: 16,
      dataPoints: [
        { x: 10, y: 71 },
        { x: 20, y: 55 },
        { x: 30, y: 50 },
        { x: 40, y: 65 },
        { x: 50, y: 95 },
        { x: 60, y: 68 },
        { x: 70, y: 28 },
        { x: 80, y: 34 },
        { x: 90, y: 14 }
      ]
    }					
  ]
});

chart.render();
drawIndexLabelLine(chart);

function drawIndexLabelLine(chart) {
	var xInPixel, yInPixel, yValue, indexLabel, indexLabelFontSize, indexLabelLineLength;	
  
  chart.ctx.beginPath();
	for(var i = 0; i < chart.data.length; i++) {
  	for(var j = 0; j < chart.data[i].dataPoints.length; j++) {
    	yValue = chart.data[i].dataPoints[j].y;
    	yInPixel = chart.axisY[0].convertValueToPixel(yValue);
      xInPixel = chart.axisX[0].convertValueToPixel(chart.data[i].dataPoints[j].x);      
      indexLabelLineLength = chart.options.data[i].indexLabelLineLength || 20;
      indexLabelFontSize = chart.options.data[i].indexLabelFontSize || 16;
      
      chart.ctx.strokeStyle = chart._selectedColorSet[i];
      chart.ctx.moveTo(xInPixel, yInPixel);
      chart.ctx.lineTo(xInPixel, yInPixel + indexLabelLineLength) ;
      chart.ctx.stroke();
      
      indexLabel = yValue.toString();
      chart.ctx.fillStyle = chart._selectedColorSet[i];
      chart.ctx.font = indexLabelFontSize + "px Arial";
      chart.ctx.textAlign = "center";
      chart.ctx.fillText(indexLabel, xInPixel, yInPixel + indexLabelLineLength) ;
    }
  }
}