chartjs-plugin-crosshair
chartjs-plugin-crosshair copied to clipboard
Using the scrollwheel to zoom.
From what I see from the code base there is currently no ways to use the scrollwheel to zoom.
Is this a feature that is planned to be released? If not, how would you implement such a feature?
Thanks
While the plugin does not support scrolling with the mouse wheel, it is possible to implement it.
All you need is to call the plugins doZoom
method
const chart = new Chart(...);
const plugin = Chart.plugins.getAll().find((p) => p.id === "crosshair");
plugin.doZoom(chart, myZoomStart, myZoomEnd);
Here is a simple version that zooms by 10% https://codepen.io/danmana/pen/GRZQNpR?editors=1010 You might want to implement a smarter way to calculate myZoomStart/End that takes into account the current mouse position (see center variable below)
canvas.addEventListener("wheel", (event) => {
const delta = event.deltaY;
const xscale = chart.scales['x-axis-0'];
const start = chart.crosshair.start === undefined ? xscale.min : chart.crosshair.start;
const end = chart.crosshair.end === undefined ? xscale.max : chart.crosshair.end;
const ZOOM_FACTOR = 0.1; // 10%
const increment = Math.sign(delta) * Math.abs(end - start) * ZOOM_FACTOR / 2;
// might want to use chart.crosshair.x and center to zoom around the current mouse position
const center = xscale.getValueForPixel(chart.crosshair.x);
const myZoomStart = start + increment;
const myZoomEnd = end - increment;
console.log(delta, start, end, center, increment, myZoomStart, myZoomEnd);
plugin.doZoom(
chart,
myZoomStart,
myZoomEnd
);
});
const plugin = Chart.plugins.getAll().find((p) => p.id === "crosshair");
How should code been rewriting for versions 3.x.x?
Chart.js 3.x.x update
Obtaining the plugin is a bit easier now:
const plugin = Chart.registry.getPlugin('crosshair');
Note: there were some changes in Chart.js v3 regarding scales. Besides that, the code above is unchanged.
const xscale = chart.scales['x'];
See example: https://codepen.io/danmana/pen/QWQjVZb?editors=1010