[Chartjs]-Implement chartjs zoom with buttons

0๐Ÿ‘

You can use an event handler to check/update the ticks of the xAxes, to achieve a similar effect:

$('#zoom_in').click(function(){
    ticks = myChart.chart.options.scales.xAxes[0].ticks;

    /* if x-axis is categorical, use the data.labels to determine current axis range, e.g.:
    labels = myChart.chart.data.labels; 
    startTick = labels.indexOf(ticks.min);
    endTick = labels.indexOf(ticks.max);
    */

    // below assumes ticks.min and ticks.max are numeric
    var diff = ticks.max - ticks.min;
    var factor = 0.05;

    var newMin = ticks.min + factor * diff;
    var newMax = ticks.max - factor * diff;

    ticks.min = newMin;
    ticks.max = newMax;  
    myChart.update();
});

0๐Ÿ‘

Values โ€‹โ€‹need to be changed to chart.config.options.scales.x

 document.getElementById("lastDays").onclick = ()=> {
        ticks = chart.config.options.scales.x;
        ticks.min = lastDaysMs;
        ticks.max = nowTime;
        chart.update();
      };

0๐Ÿ‘

There are several options to zoom in, out and reset.
All answers above seem correct.
Nevertheless, I found the easiest one to be

  1. Get the chart in a variable.
  2. zoomIn โ€“> myChart.zoom(1.1) // 1.1 is just a random zoom in value to scale up
  3. zoomOut โ€“> myChart.zoom(0.9) // scale down
  4. reset โ€“> myChart.resetZoom() // reset the chart.

Leave a comment