NASA Working Line Drag
Draw Line on Chart based on Mouse Events - CanvasJS JavaScript Charts
by santy_naren
HTML
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>
JavaScript
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
title: {
text: "Smazee Lines"
},
data: [
{
type: "column",
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 line, isDown ;
var store = new Array();
var lineCoordinates = {};
var parentOffset = $(chart.container).offset();
jQuery(chart.container).on({
mousedown: function(e) {
isDown = true;
var points = [e.clientX - parentOffset.left, e.clientY - parentOffset.top, e.clientX - parentOffset.left, e.clientY - parentOffset.top ];
lineCoordinates.x1 = e.clientX - parentOffset.left;
lineCoordinates.y1 = e.clientY - parentOffset.top;
},
mouseup: function(e) {
isDown = false;
console.log(lineCoordinates);
store.push({x1:lineCoordinates.x1,y1:lineCoordinates.y1,x2:lineCoordinates.x2,y2:lineCoordinates.y2});
console.log(store);
},
mousemove: function(e){
if (!isDown) return;
lineCoordinates.x2 = e.clientX - parentOffset.left;
lineCoordinates.y2 = e.clientY - parentOffset.top;
refresh();
drawLine(chart, lineCoordinates);
}
});
function refresh(){
chart.render();
for(var r=0;r<store.length;r++){
var ctx = chart.ctx;
ctx.beginPath();
ctx.strokeStyle = "#000"; //Change Line Color
ctx.lineWidth = 2; //Change Line Width/Thickness
ctx.moveTo(store[r].x1,store[r].y1);
ctx.lineTo(store[r].x2,store[r].y2);
ctx.stroke();
}
}
function drawLine(chart, lineCoordinates) {
var ctx = chart.ctx;
ctx.beginPath();
ctx.strokeStyle = "#000"; //Change Line Color
ctx.lineWidth = 2; //Change Line Width/Thickness
ctx.moveTo(lineCoordinates.x1,lineCoordinates.y1);
ctx.lineTo(lineCoordinates.x2,lineCoordinates.y2);
ctx.stroke();
}