Draggable bubble chart - CanvasJS JavaScript Charts
Draggable bubble chart - 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 chart = new CanvasJS.Chart("chartContainer",{
axisX:{
minimum: 5,
maximum: 95
},
title: {
text: "Try dragging column to reposition dataPoint",
},
data: [
{
type: "bubble",
dataPoints: [
{ x: 10, y: 71, z: 1 },
{ x: 20, y: 55, z: 2 },
{ x: 30, y: 50, z: 3 },
{ x: 40, y: 65, z: 2 },
{ x: 50, y: 95, z: 1 },
{ x: 60, y: 68, z: 4 },
{ x: 70, y: 28, z: 3 },
{ x: 80, y: 34, z: 2 },
{ x: 90, y: 14, z: 1 }
]
}
]
});
chart.render();
var xSnapDistance = 5;
var ySnapDistance = 3;
var xValue, yValue;
var mouseDown = false;
var selected = 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 = 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 - ySnapDistance && yValue <= dps[i].y + ySnapDistance) ) {
if(mouseDown) {
selected = i;
break;
}
else {
changeCursor = true;
break;
}
} else {
selected = null;
changeCursor = false;
}
}
}
jQuery("#chartContainer > .canvasjs-chart-container").on({
mousedown: function(e) {
mouseDown = true;
getPosition(e);
searchDataPoint();
},
mousemove: function(e) {
getPosition(e);
if(mouseDown) {
clearTimeout(timerId);
timerId = setTimeout(function(){
if(selected != null) {
chart.data[0].dataPoints[selected].y = yValue;
chart.render();
}
},...