[Chartjs]-Chart.js get array of currently visible points on graph

3👍

The chart object contains minIndex and maxIndex properties that can be used to slice the dataset for the visible values.

Here’s a snippet showing how to use the plugin-provided functions onPanComplete and onZoomComplete to output the visible values after panning or zooming the chart:

function getVisibleValues({
  chart
}) {
  let x = chart.scales["x-axis-0"];

  document.getElementById("vv").innerText = JSON.stringify(chart.data.datasets[0].data.slice(x.minIndex, x.maxIndex + 1));
}

new Chart(document.getElementById("chart"), {
  type: "line",
  data: {
    labels: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'],
    datasets: [{
      data: [0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
    }]
  },
  options: {
    maintainAspectRatio: false,
    scales: {
      xAxes: [{
        ticks: {
          min: 'c',
          max: 'h'
        }
      }]
    },
    plugins: {
      zoom: {
        pan: {
          enabled: true,
          mode: 'x',
          onPanComplete: getVisibleValues
        },
        zoom: {
          enabled: true,
          mode: 'x',
          onZoomComplete: getVisibleValues
        }
      }
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.1"></script>
<script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@0.7.4"></script>
<canvas id="chart" style="max-height:125px"></canvas>
<p>
  Visible values: <span id="vv"></span>
</p>

0👍

The toBase64Image function does not what you want, it just gets the data URL from the canvas.

toBase64Image on github.com/chartjs

toBase64Image: function() {
  return this.canvas.toDataURL.apply(this.canvas, arguments);
},

You can get the updated chart data with onZoomComplete and onPanComplete, they both get an object that contains chart from this you might get more information about the current zoom, but as far as I can see you will need to do some calculations/work to get the visible points…

Leave a comment