Chart.js drag points on linear chart - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Chart.js drag points on linear chart

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>ChartJS Line Chart</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.js"></script> 
      <script type="text/javascript" src="https://d3js.org/d3-drag.v1.min.js"></script> 
      <script type="text/javascript" src="https://d3js.org/d3-selection.v1.min.js"></script> 
      <script type="text/javascript" src="https://d3js.org/d3-dispatch.v1.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*from  ww  w  .  j  av  a 2s  .co m*/
var options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [
       {
         label: '# of Votes',
         data: [12, 19, 3, 5, 2, 3],
         borderWidth: 1
       },
         {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            borderWidth: 1
         }
      ]
  },
  options: {
     scales: {
       yAxes: [{
        ticks: {
               reverse: false
        }
      }]
    }
  }
}
var ctx = document.getElementById('chartJSContainer').getContext('2d');
var chartInstance = new Chart(ctx, options);
d3.select(chartInstance.chart.canvas).call(
  d3.drag().container(chartInstance.chart.canvas)
    .on('start', getElement)
    .on('drag', updateData)
    .on('end', callback)
);
var element, scale, datasetIndex, index, value
function getElement () {
   var e = d3.event.sourceEvent
   element = chartInstance.getElementAtEvent(e)[0]
  scale = element['_yScale'].id
}
function updateData () {
   var e = d3.event.sourceEvent
  datasetIndex = element['_datasetIndex']
  index = element['_index']
  value = chartInstance.scales[scale].getValueForPixel(e.clientY)
  chartInstance.data.datasets[datasetIndex].data[index] = value
  chartInstance.update(0)
}
function callback () {
  return console.log('The new value is: ' + value)
}
    }

      </script> 
   </head> 
   <body>  
      <canvas id="chartJSContainer" width="600" height="400"></canvas>   
   </body>
</html>

Related Tutorials