Add Stripline Dynamically in Area Chart based on Mouse Events | CanvasJS JavaScript Charts

Add Stripline Dynamically in Area Chart based on Mouse Events | 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 selected = -1;
var chart = new CanvasJS.Chart("chartContainer", {
  theme: "light2",
  title: {
    text: "Area Chart with Dynamic Stripline"
  },
  subtitles: [{
    text: "Drag mouse anywhere on the plot-area to add stripline"
  }],
  axisX: [{
    stripLines: []
  }],
  data: [{
    type: "area",
    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 startValue, endValue;
$(".canvasjs-chart-canvas").last().on("mousedown", function(e) {  
  var parentOffset = $(this).parent().offset();
  var relX = e.pageX - parentOffset.left;
  var relY = e.pageY - parentOffset.top;
  chart.options.axisX[0].stripLines = []; //Comment this line to add as many stripLine based on mouse events than single stripline
  startValue = chart.axisX[0].convertPixelToValue(relX);
});

$(".canvasjs-chart-canvas").last().on("mouseup", function(e) {
  var parentOffset = $(this).parent().offset();
  var relX = e.pageX - parentOffset.left;
  var relY = e.pageY - parentOffset.top;

  endValue = chart.axisX[0].convertPixelToValue(relX);
  if(startValue === endValue)
    chart.options.axisX[0].stripLines.push({value: startValue });
  else
    chart.options.axisX[0].stripLines.push({startValue: startValue, endValue: endValue});
  chart.render();
});