[Chartjs]-Chart.js zoom start at zoomed in

2👍

ChartJS doesn’t have setZoom method in-built. Issue that sums up ChartJS zoom plugin limitations: https://github.com/chartjs/chartjs-plugin-zoom/issues/82

Here is a hack way to send mouse wheel event to the chart and zoom:

let e = document.createEvent('MouseEvents')
e.initEvent('wheel', true, true)
e.deltaY = -10e20;
setTimeout(() => {
  for(let i=0;i<70;i++)
    canvas.dispatchEvent(e);
}, 500);

Hope this helps.

1👍

Finally worked this out.

In the scales options section you need to add a min integer when used with the zoom function this then still renders the graph outside of the canvas, ready for panning.

scales: {
         xAxes:[
                 {
                    type: 'time',
                    time: {
                    min: '2',
                    tooltipFormat: 'll',
                    displayFormats: {
                    quarter: 'MMM YYYY',
                }
            },

As long as your “Type” is time this worked for me.

0👍

Here is a full answer to the partial solution above.

I will assume we have years of data in a time based chart. It is too much to see in a big chart. So we will open the chart showing only the most recent year of data.

You need to set chart options for both scales and the zoom plugin.

Firstly, we set the scales to be a minimum that is a date from a year ago. (like in the @user372531 answer above)

 scales: {
      x: {
          type: "time",
          min: oneYearAgo, 
       }

This will make the chart open and display the most recent year of data. You don’t need to set a max, it will default to your latest data.

You should find your chart opens zoomed in to one year of data! However you will not be able to zoom or pan out… yet!

Secondly, set the widest limits in your zoom plugin options:

zoom: {
        zoom: {
          wheel: {enabled: true,},
          mode: 'x',   
        },
        pan: {
          enabled: true,
          mode: 'x',
        },
        limits: {
          x: { min: oldestDataDate, max: newestDataDate },
        },
      },

(I’ve given my full zoom/pan options for controlling the horizontal time axis only)

This will also load your chart much quicker.

Leave a comment