Draggable Range Bar Chart - Resizable from both sides | Canvas JavaScript

Draggable Range Bar Chart - Resizable from both sides | Canvas JavaScript

by canvasjs

HTML

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

JavaScript

var chart = new CanvasJS.Chart("chartContainer",{        
  title: {
    text: "Try Dragging Any Bar to Resize",
  },
  data: [
    {
      type: "rangeBar",
      dataPoints: [
        { x: 10, y: [21, 69] },
        { x: 20, y: [34, 90] },
        { x: 30, y: [11, 74] },
        { x: 40, y: [35, 89] },
        { x: 50, y: [45, 100] },
        { x: 60, y: [28, 90] },
        { x: 70, y: [28, 76] },
        { x: 80, y: [34, 78] },
        { x: 90, y: [14, 65] }
      ]
    }                   
  ]
});

chart.render();

var xSnapDistance = 2;
var ySnapDistance = 3;

var xValue, yValue;

var mouseDown = false;
var selected = null;
var yIndex = null;
var changeCursor = false;

var timerId = null;

function getPosition(e) {
  var parentOffset = $("#chartContainer > .canvasjs-chart-container").offset();          	
  var relX = e.pageX - parentOffset.left;
  var relY = e.pageY - parentOffset.top;
  xValue = Math.round(chart.axisX[0].convertPixelToValue(relY));
  yValue = Math.round(chart.axisY[0].convertPixelToValue(relX));
}

function searchDataPoint() {
  var dps = chart.data[0].dataPoints;
  for(var i = 0; i < dps.length; i++ ) {
  	
    if( (xValue >= dps[i].x - xSnapDistance && xValue <= dps[i].x + xSnapDistance) && 
       (yValue >= dps[i].y[0] - ySnapDistance && yValue <= dps[i].y[0] + ySnapDistance) ) {
      if(mouseDown) {
        selected = i;
        yIndex = 0;
        break;
      }
      else {
        changeCursor = true;
        break; 
      }
    } 
     else if( (xValue >= dps[i].x - xSnapDistance && xValue <= dps[i].x + xSnapDistance) && 
       (yValue >= dps[i].y[1] - ySnapDistance && yValue <= dps[i].y[1] + ySnapDistance) ) {
      if(mouseDown) {
        selected = i;
        yIndex = 1;
        break;
      }
      else {
        changeCursor = true;
        break; 
      }
    } else {
      selected = null;
      changeCursor = false;
    }
  }
}

jQuery("#chartContainer > .canvasjs-chart-container").on({
  mousedown: function(e) {
   ...