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

后端 未结 1 654
臣服心动
臣服心动 2021-01-21 14:33

I have a chart like this:

Now I need to find the minimum and maximum labels that are inside a pan, when I zoom, for example:

The minimum woul

相关标签:
1条回答
  • 2021-01-21 15:04

    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>

    0 讨论(0)
提交回复
热议问题