JSFiddle - React, Tailwind, and code Playground

by Ragu Nathan

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
<button id="find">Find distance </button>
<button id="remove">Remove </button>

JavaScript

window.onload = function () {
  var chart = new CanvasJS.Chart("chartContainer", {
    title: {
      text: "Stripline on  Axis X"
    },
    axisX:{
      stripLines:[
        {                
          value: 1935
        }, {                
          value: 1945
        }
      ],
      valueFormatString: "####"
    },
    data: [
      {
        type: "splineArea",            
        color: "rgba(83, 223, 128, .6)",
        dataPoints: [
          { x: 1910, y: 5 }, 
          { x: 1920, y: 9 }, 
          { x: 1930, y: 17}, 
          { x: 1940, y: 32}, 
          { x: 1950, y: 22}, 
          { x: 1960, y: 14}, 
          { x: 1970, y: 25}, 
          { x: 1980, y: 18}, 
          { x: 1990, y: 20}
        ]
      }
    ]        
  });
  chart.render();
  
  document.getElementById("find").addEventListener("click", function(){
    var striplines = chart.axisX[0].stripLines;
    var viewport = (chart.axisY[0].viewportMaximum - chart.axisY[0].viewportMinimum) / chart.options.data.length;

    chart.addTo("data", {
      type: "line",
      toolTipContent: null,
      highlightEnabled: false,
      markerSize: 0,
      name: 'distance',
      dataPoints: [
        { x: striplines[0].get("value"), y: viewport },
        { x: (striplines[1].get("value") + striplines[0].get("value")) / 2, y: viewport, indexLabel:  (striplines[1].get("value") - striplines[0].get("value")).toString()},
        { x: striplines[1].get("value"), y: viewport }
      ]
    });
  });
  
  document.getElementById("remove").addEventListener("click", function(){
  for(var i = chart.options.data.length - 1; i >= 0; i--) {
  	if (chart.options.data[i].name === 'distance') {
 			chart.data[i].remove();
    }
  }
  });
}