Chart with Multiple Draggable stripLines - CanvasJS JavaScript Charts

Chart with Multiple Draggable stripLines - 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", {        
    title: {
      	text: "Chart with Draggable stripLines"
    },
    axisX: [{
        stripLines: [{
          	value: 10
        }, {
          	value: 30
        }, {
          	value: 70
        }]
    }],
    data: [{
        type: "line",
        dataPoints: [
            { x: 10, y: 710 },
            { x: 20, y: 550 },
            { x: 30, y: 500 },
            { x: 40, y: 650 },
            { x: 50, y: 950 },
            { x: 60, y: 680 },
            { x: 70, y: 280 },
            { x: 80, y: 340 },
            { x: 90, y: 140 }
        ]
    }]
});

chart.render();

$(".canvasjs-chart-canvas").last().on("mousedown", function(e) {
		// Get the selected stripLine & change the cursor
    var parentOffset = $(this).parent().offset();
		var relX = e.pageX - parentOffset.left;
    var relY = e.pageY - parentOffset.top;
    var snapDistance = 5;
    
  	for(var i = 0; i < chart.options.axisX[0].stripLines.length; i++) {
    	if(relX > chart.axisX[0].stripLines[i].get("bounds").x1 - snapDistance && relX < chart.axisX[0].stripLines[i].get("bounds").x2 + snapDistance && relY > chart.axisX[0].stripLines[i].get("bounds").y1 && relY < chart.axisX[0].stripLines[i].get("bounds").y2) {
        selected = i;
        $(this).css("cursor","pointer");
    	}
  	}
});

$(".canvasjs-chart-canvas").last().on("mousemove", function(e) {
		// Move the selected stripLine
    if(selected !== -1) {
    	var parentOffset = $(this).parent().offset();
			var relX = e.pageX - parentOffset.left;
      chart.options.axisX[0].stripLines[selected].value = chart.axisX[0].convertPixelToValue(relX);
     	chart.render();
    }
});

$(".canvasjs-chart-canvas").last().on("mouseup", function(e) {
		// Clear Selection and change the cursor
    selected = -1;
    $(this).css("cursor","default");
});