chartjs-plugin-streaming #79

by Akihiko Kusanagi

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-streaming"></script>
<canvas id="chart"></canvas>

JavaScript

new Chart(document.getElementById('chart'), {
  type: 'line',
  data: {
    datasets: [{
      label: 'Dataset 1 (linear interpolation)',
      backgroundColor: "red",
      borderColor: "yellow",
      fill: false,
      lineTension: 0,
      borderDash: [8, 4],
      data: [
        {y: 0.74, x: 1558531380957},
        {y: 0.96, x: 1558531379950},
        {y: 1.08, x: 1558531378942},
        {y: 1.11, x: 1558531377939},
      ]
    }, {
      label: 'Dataset 2 (cubic interpolation)',
      backgroundColor: "pink",
      borderColor: "green",
      fill: false,
      cubicInterpolationMode: 'monotone',
      data:[
        {y: 0.74, x: 1558531380957},
        {y: 0.96, x: 1558531379950},
        {y: 4.08, x: 1558531378942},
        {y: 0.11, x: 1558531377939},
        {y: 0.13, x: 1558531376932},
      ]
    }]
  },
  options: {
    scales: {
      xAxes: [{
        type: 'time',
        realtime: {
          duration: 20000,
          refresh: 1000,
          delay: 1000,
          pause: false,
          ttl: undefined,
          // a callback to update datasets
          onRefresh: (chart) => {
            console.log("chart");
            // append the new data array to the existing chart data
            Array.prototype.push.apply(chart.data.datasets[0].data, [{x: Date.now(), y: Math.random()}]);
          }
        }
      }]
    },
    plugins: {
      streaming: { // per-chart option
        frameRate: 30 // chart is drawn 30 times every second
      }
    }
  }
});