[Chartjs]-ChartJS line chart drag and zoom

3đź‘Ť

I didn’t find “drag and zoom” functionality for Chart.js as well as simple example with “pan and zoom” version so I’ve decided to implement demo version own my own.

List of external scripts is very important: hammer-js, then Chart.bundle.js and chartjs-plugin-zoom.js.

const config = {
  type: 'line',
  data: {
    labels: [new Date('2019-08-20'), new Date('2019-08-25'), new Date('2019-08-30')],
    datasets: [{
      label: 'Line',
      data: [2, 5, 3],
      borderColor: '#D4213D',
      fill: false,
    }, ],
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
      }, ],
    },
    pan: {
      enabled: true,
      mode: 'xy',
    },
    zoom: {
      enabled: true,
      mode: 'xy', // or 'x' for "drag" version
    },
  },
};

window.onload = function() {
  new Chart(document.getElementById('chart'), config);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-zoom/0.6.6/chartjs-plugin-zoom.js"></script>
<html>
<body>
  <div style="width:380px;">
    <canvas id="chart"></canvas>
  </div>
</body>
</html>

If someone is interesting in other libraries, I found one interesting solution on Vicotry website with “brush and zoom” functionality for line charts: https://formidable.com/open-source/victory/guides/brush-and-zoom/.

EDIT: In the “drag” version you will have to use for zoom:

drag: {
   borderColor: 'hsl(35, 100%, 60%)',
   borderWidth: '3',
   backgroundColor: 'hsl(35, 100%, 60%)',
},

Leave a comment