NASA Working Line Drag Snap
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 y1;
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;
y1 = e.clientY - parentOffset.top
lineCoordinates.y1 = e.clientY - parentOffset.top;
console.log(y1);
},
mouseup: function(e) {
isDown = false;
y1 = 0;
console.log(lineCoordinates);
store.push({
x1: lineCoordinates.x1,
y1: lineCoordinates.y1,
x2: lineCoordinates.x2,
y2: lineCoordinates.y2
});
console.log(y1);
console.log(store);
var ctx = chart.ctx;
ctx.beginPath();
ctx.arc(lineCoordinates.x2, lineCoordinates.y2, 5, 0, 2 * Math.PI);
ctx.stroke();
},
mousemove: function(e) {
if (!isDown) return;
lineCoordinates.x2 = e.clientX - parentOffset.left;
lineCoordinates.y2 = e.clientY - parentOffset.top;
console.log(y1);
if(y1 > lineCoordinates.y2){
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
...