CanvasJS Chart - Mouse-Wheel Zoom-In / Zoom-Out
CanvasJS Chart - Mouse-Wheel Zoom-In / Zoom-Out
by Vishwas .R
HTML
<script src="https://cdn.canvasjs.com/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
JavaScript
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2",
zoomEnabled: true,
title: {
text: "CanvasJS Chart with Mouse-Wheel Zoom"
},
axisX: {
title: "X Axis Title"
},
axisY: {
title: "Y Axis Title"
},
data: [{
type: "line",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}]
});
chart.render();
bindMouseWheelZoom(chart);
function bindMouseWheelZoom(chart) {
chart.overlaidCanvas.addEventListener("wheel", function (e) {
e.preventDefault();
var zoomFactor = 0.1; // Change Zoom-Factor
if (e.offsetX < chart.plotArea.x1 || e.offsetX > chart.plotArea.x2 || e.offsetY < chart.plotArea.y1 || e.offsetY > chart.plotArea.y2)
return;
var xValue = Math.round(chart.axisX[0].convertPixelToValue(e.offsetX));
var yValue = Math.round(chart.axisY[0].convertPixelToValue(e.offsetY));
var axisXViewportMin = chart.axisX[0].get("viewportMinimum"),
axisXViewportMax = chart.axisX[0].get("viewportMaximum"),
axisXMin = chart.axisX[0].get("minimum"),
axisXMax = chart.axisX[0].get("maximum");
var newAxisXViewportMin, newAxisXViewportMax;
if (e.deltaY < 0) {
newAxisXViewportMin = axisXViewportMin + (xValue - axisXViewportMin) * zoomFactor;
newAxisXViewportMax = axisXViewportMax - (axisXViewportMax - xValue) * zoomFactor;
} else if (e.deltaY > 0) {
newAxisXViewportMin = (axisXViewportMin - (xValue - axisXViewportMin) * zoomFactor) >= axisXMin ? (axisXViewportMin - (xValue - axisXViewportMin) * zoomFactor) : axisXMin;
newAxisXViewportMax = (axisXViewportMax + (axisXViewportMax - xValue) * zoomFactor) <= axisXMax ? (axisXViewportMax + (axisXViewportMax - xValue) * zoomFactor) : axisXMax;
}
if (newAxisXViewportMin >= axisXMin && newAxisXViewportMax <=...