Draw Line on Chart based on Mouse Events - CanvasJS JavaScript Charts

Draw Line on Chart based on Mouse Events - CanvasJS JavaScript Charts

by santy_naren

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

JavaScript

var chart = new CanvasJS.Chart("chartContainer", {
	theme: "light2",
	title: {
  	text: "Draw Line on Chart based on Mouse Events"
  },  
  data: [
    {
      type: "column",
      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();

var lineCoordinates = {};
var parentOffset = $(chart.container).offset();
jQuery(chart.container).on({
  mousedown: function(e) {
    lineCoordinates.x1 = e.clientX - parentOffset.left;
    lineCoordinates.y1 = e.clientY - parentOffset.top;    
  },
  mouseup: function(e) {
    lineCoordinates.x2 = e.clientX - parentOffset.left;
    lineCoordinates.y2 = e.clientY - parentOffset.top;
    drawLine(chart, lineCoordinates);
  }
});

function drawLine(chart, lineCoordinates) {
  var ctx = chart.ctx;

  ctx.beginPath();
  ctx.strokeStyle = "#000"; //Change Line Color
  ctx.lineWidth = 2; //Change Line Width/Thickness
  ctx.moveTo(lineCoordinates.x1,lineCoordinates.y1);
  ctx.lineTo(lineCoordinates.x2,lineCoordinates.y2);
  ctx.stroke();
}