chartjs-plugin-streaming #116

by Akihiko Kusanagi

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="chart"></canvas>

JavaScript

var chart = new Chart(document.getElementById('chart'), {
  type: 'line',
  data: {
    datasets: [{
      data: [],
      label: 'Dataset 1',
      borderColor: 'rgb(255, 99, 132)',
      backgroundColor: 'rgba(255, 99, 132, 0.5)',
      borderDash: [8, 4]
    }, {
      data: [],
      label: 'Dataset 2',
      borderColor: 'rgb(54, 162, 235)',
      backgroundColor: 'rgba(54, 162, 235, 0.5)',
      cubicInterpolationMode: 'monotone'
    }]
  },
  options: {
    scales: {
      x: {
        type: 'realtime',
        realtime: {
          onRefresh: function(chart) {
            chart.data.datasets.forEach(function(dataset) {
              dataset.data.push({
                x: Date.now(),
                y: Math.random()
              });
            });
          },
          pause: false
        }
      }
    }
  },
  plugins: [{
    beforeEvent: function(chart, args) {
      var realtimeOpts = chart.options.scales.x.realtime;
      var event = args.event;
      var isPointInArea;

      if (event.type === 'mousemove') {
        isPointInArea = Chart.helpers._isPointInArea(event, chart.chartArea);
      } else if (event.type === 'mouseout') {
        isPointInArea = false;
      }
      if (isPointInArea !== undefined && realtimeOpts.pause !== isPointInArea) {
        realtimeOpts.pause = isPointInArea;
        chart.update('none');
      }
      return false;
    }
  }]
});