JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://rawgit.com/nnnick/Chart.js/master/dist/Chart.js"></script>
<script src="https://hammerjs.github.io/dist/hammer.min.js"></script>
<canvas id="canvas"></canvas>
JavaScript
var helpers = Chart.helpers;
function canZoomDirection(mode, dir) {
if (mode === undefined) {
return true;
} else if (typeof mode === 'string') {
return mode.indexOf(dir) !== -1;
}
return false;
}
function zoomScaleIn(scale, zoom, center) {
if (typeof scale.min === 'number' && typeof scale.max === 'number') {
var newDiff = (scale.max - scale.min) * (zoom - 1);
scale.options.ticks.min = scale.min + (newDiff / 2);
scale.options.ticks.max = scale.max - (newDiff / 2);
} else {
// Category scale
var indexDiff = scale.maxIndex - scale.minIndex;
}
}
function doZoom(chartInstance, zoom, center) {
var ca = chartInstance.chartArea;
if (!center) {
center = {
x: (ca.left + ca.right) / 2,
y: (ca.top + ca.bottom) / 2,
}
}
if (chartInstance.options.zoom && chartInstance.options.zoom.enabled) {
// Do the zoom here
helpers.each(chartInstance.scales, function(scale, id) {
if (scale.isHorizontal() && canZoomDirection(chartInstance.options.zoom.mode, 'x')) {
zoomScaleIn(scale, zoom, center);
} else if (canZoomDirection(chartInstance.options.zoom.mode, 'y')) {
// Do Y zoom
zoomScaleIn(scale, zoom, center);
}
});
chartInstance.update();
}
}
// Chartjs Zoom Plugin
var ZoomPlugin = Chart.PluginBase.extend({
beforeInit: function(chartInstance) {
var node = chartInstance.chart.ctx.canvas;
var options = chartInstance.options;
var wheelHandler = function(e) {
if (e.wheelDelta > 0) {
doZoom(chartInstance, 1.1);
} else {
doZoom(chartInstance, 0.909);
}
};
chartInstance._wheelHandler = wheelHandler;
node.addEventListener('mousewheel', wheelHandler);
var mc = new window.Hammer.Manager(node);
mc.add(new Hammer.Pinch());
var handlePinch = function handlePinch(e) {
var diff = 1 / (currentPinchScaling) * e.scale;
doZoom(chartInstance, diff, e.center);
// Keep track of...