chartjs / chartjs-plugin-zoom

Zoom and pan plugin for Chart.js
MIT License
598 stars 327 forks source link

Chartjs-plugin-zoom drag issue #807

Closed bjlee3075 closed 2 weeks ago

bjlee3075 commented 9 months ago

Hi I am drawing a graph using chart.js. Below is my code. zoom works fine. However, there is a little problem. If the mouse leaves the chart while dragging, it will not zoom in properly. Like the first picture, the starting point of the drag is 2023, and the end of the drag is outside the chart, not inside the chart. The starting point of drag is 2023, but as shown in the second picture, 2011 became the starting point. Is there any way to prevent this?

Thanks,

2 1

        zoom: {
            pan: {
                enabled: false,
                mode: 'x',
            },
            zoom: {
                wheel: {
                    enabled: false,
                },
                pinch: {
                    enabled: false,
                },
                drag: {
                    enabled: true,
                    mode: 'x',
                    borderColor: 'rgba(0, 0, 0, 0.5)', 
                    borderWidth: 1, 
                    backgroundColor: 'rgba(0, 0, 0, 0.3)',
                },
                mode: 'x',

                onZoomComplete: function (context) {
                    const chart = context.chart;
                    const xScale = chart.scales.x;
                    const displayedRange = xScale.max - xScale.min;
                    const oneYear = 1000 * 60 * 60 * 24 * 365;
                    isLongRange = displayedRange >= oneYear * 10;

                    chart.options.scales.x.time.unit = 'month';

                    if (displayedRange < oneYear * 3) {
                        chart.options.scales.x.ticks.stepSize = 1;
                    } else if (displayedRange < oneYear * 6) {
                        chart.options.scales.x.ticks.stepSize = 2;
                    } else if (displayedRange < oneYear * 10) {
                        chart.options.scales.x.ticks.stepSize = 6;
                    } else {
                        chart.options.scales.x.time.unit = 'year';
                        delete chart.options.scales.x.ticks.stepSize; 
                    }

                    chart.update();
                },
            },
            limits: { 
                x: {
                    min: new Date(originalXMin).getTime(), 
                    max: new Date(originalXMax).getTime() 
                }
            },
        },