[Chartjs]-Charts how to find local bounds of a zoomed chart

2👍

You can get the min and max from the scale itself from the chart object you get as a parameter on the zoom callback like so:

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      zoom: {
        zoom: {
          onZoom: ({
            chart
          }) => {
            const xMin = chart.scales.x.getLabelForValue(chart.scales.x.min);
            const xMax = chart.scales.x.getLabelForValue(chart.scales.x.max);
            const yMin = chart.scales.y.min;
            const yMax = chart.scales.y.max;

            console.log(xMin, xMax, yMin, yMax)
          },
          wheel: {
            enabled: true
          }
        }
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/hammerjs@2.0.8"></script>
  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-zoom@1.2.1/dist/chartjs-plugin-zoom.js"></script>
</body>

1👍

I’m not sure 100% what you are asking here. I think you are asking if there is a way to get the scale min and max while scrolling? If you are asking that then you can use chart.getInitialScaleBounds() in the onZoom or onZoomComplete callback functions. However, if you are asking for a way to get the max scale of the current viewport after zoom… I do not think this is possible after having a good read of the docs and GitHub tickets.

https://www.chartjs.org/chartjs-plugin-zoom/latest/guide/developers.html#chart-getinitialscalebounds-record-string-min-number-max-number

https://github.com/chartjs/chartjs-plugin-zoom/discussions/586

1👍

Apparently, we can get the min and max of x values on the screen but can not get for the y value directly. We should iterate every x values to get max/min of y between the screen interval. So my code is something like :

const { data } = chart.data.datasets[0];
var xMin = 0;
var xMax = data.length;
// I set yMin as yMax to get yMin while iterating over x values
var yMin = chart.scales.y.max;
var yMax = 0;
xMin = chart.scales.x.min;
xMax = chart.scales.x.max;
              
for (let i = xMin; i < xMax; i++) {
  let y = data[i];
  yMin = Math.min(y, yMin);
  yMax = Math.max(y, yMax);
} 

So I can get the min/max of y between leftmost and rightmost pixels of the chart area.

Leave a comment