JSFiddle - React, Tailwind, and code Playground
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", {
axisX:{
minimum: 5,
maximum: 95
},
axisY: [{
title: "Prices",
prefix: "$ "
}],
title: {
text: "Try dragging to reposition dataPoint",
},
data: [
{
type: "line",
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 }
]
},
{
type: "line",
dataPoints: [
{ x: 10, y: 171 },
{ x: 20, y: 155 },
{ x: 30, y: 150 },
{ x: 40, y: 165 },
{ x: 50, y: 195 },
{ x: 60, y: 168 },
{ x: 70, y: 128 },
{ x: 80, y: 134 },
{ x: 90, y: 114 }
]
}
]
});
chart.render();
var xSnapDistance = 5; //10 percentage
var ySnapDistance = 5; //10 percentage
var xValue, yValue, yValueDifference;
var mouseDown = false;
var selectedDataPoint = null, selectedDataSeries = 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(relX));
yValue = Math.round(chart.axisY[0].convertPixelToValue(relY));
}
function searchDataPoint() {
var dps = [];
for(var j = 0; j < chart.data.length; j++) {
dps = chart.data[j].dataPoints;
for(var i = 0; i < dps.length; i++ ) {
if( (xValue >= dps[i].x - xSnapDistance && xValue <= dps[i].x + xSnapDistance) &&
(yValue >= dps[i].y - ySnapDistance && yValue <= dps[i].y + ySnapDistance ) ) {
if(mouseDown) {
selectedDataPoint = i;
selectedDataSeries = j;
break;
}
else {
changeCursor = true;
break;
}
} else {
...