Chartjs-How to stop chartjs zoom more than visible points?

0👍

In case anyone facing about the same issue, I found a solution to this. After zoom, we can set the chart to its closest left and right points by overriding its original zoom functionality in onZoom function. please find the answer.

         zoom: {
                    enabled: true,
                    drag: true,
                    sensitivity: 0.5,
                    mode: "x",
                    threshold: 0,
                    rangeMax: {
                        x: end_date,
                    },
                    rangeMin: {
                        x: start_date,
                    },
                    onZoom: function () {
                        debugger
                        console.log("zoom");
                        var leftEnd = myChartRef.current.chartInstance.getDatasetMeta(0).dataset._scale.chart.scales['xAxis']._table[0].time;
                        var rightEnd = myChartRef.current.chartInstance.getDatasetMeta(0).dataset._scale.chart.scales['xAxis']._table[1].time;

                        var labels = myChartRef.current.chartInstance.chart.config.data.labels


                        var closestleft = labels.reduce(function (prev, curr) {
                            return (Math.abs(curr - leftEnd) < Math.abs(prev - leftEnd) ? curr : prev);
                        });
                        var closestRight = labels.reduce(function (prev, curr) {
                            return (Math.abs(curr - rightEnd) > Math.abs(prev - rightEnd) ? curr : prev);
                        });
                        myChartRef.current.chartInstance.options.scales.xAxes[0].time.min = closestleft
                        myChartRef.current.chartInstance.options.scales.xAxes[0].time.max = closestRight
                        myChartRef.current.chartInstance.update()

                        console.log(leftEnd)
                        console.log(rightEnd)
                    }
                },

Kudos!

Leave a comment