[Chartjs]-ChartJS – Finding the minimum and maximum labels that are inside a pan (When zooming)

4👍

I assume you’re using chartjs-plugin-zoom for this.

Digging around in the chart object passed to the onPanComplete function reveals that the scales property is updated to achieve the zoom’n’pan functionality. Knowing this, it’s fairly trivial to retrieve the first and last tick objects which contain the label property you’re looking for.

Below is a snippet that demonstrates accessing the ticks via onPanComplete and outputting them to the page:

let ft = document.getElementById("ft"),
  lt = document.getElementById("lt");

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: function({
            chart
          }) {
            let ticks = chart.scales["x-axis-0"]._ticks;
            ft.innerText = JSON.stringify(ticks[0]);
            lt.innerText = JSON.stringify(ticks[ticks.length - 1]);
          }
        }
      }
    }
  }
});
<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>
  First tick: <span id="ft"></span><br>Last tick: <span id="lt"></span>
</p>

Leave a comment