Zooming with scroll wheel in CanvasJS

1.2k views Asked by At

I am using this script to draw line charts :

  function processData(allText) {
            var allLinesArray = allText.split('\r\n');
            if(allLinesArray.length>0){
                    var dataPoints = [];
                    for (var i = 1; i <= allLinesArray.length-1; i++) {
                            var rowData = allLinesArray[i].split(';');
                            dataPoints.push({label:rowData[0],y:parseInt(rowData[1])});
                    }
                    drawChart(dataPoints);


            }
    }

    function drawChart( dataPoints) {
            var chart = new CanvasJS.Chart("chartContainer", {
            theme: "theme2",
zoomEnabled:true,
            title:{
                    text: "RPM"
            },
legend: {
horizontalAlign: "right",
verticalAlign: "center"
},
            data: [
            {
                    type: "line",
                    dataPoints: dataPoints
            }]
            });

            chart.render();
    }

The current code is zooming upon mouse click and dragging the zone. How to change it so I can zoom with the scroll wheel?

1

There are 1 answers

0
Roman Jokl On

Note the following use undocumented internals from CanvasJS and can break in the future.

  1. attach mousewheel event handler:

    var chartContainer = document.getElementById("chartContainer");
    if (chartContainer.addEventListener) {
        // IE9, Chrome, Safari, Opera
        chartContainer.addEventListener("mousewheel", (e)=>this.MouseWheelHandler(e), false);
        // Firefox
        chartContainer.addEventListener("DOMMouseScroll", (e)=>this.MouseWheelHandler(e), false);
    }
    
  2. implement handler

    MouseWheelHandler(e) {
    
    let dir : number = (e.wheelDelta || -e.detail) > 0 ? -1 : +1;
    let b = this.chartV._axes.find((a: any) => {return a.type == 'axisX'});
    let delta : number = dir * (b.viewportMaximum - b.viewportMinimum) / 10;
    b.sessionVariables.newViewportMinimum = b.viewportMinimum - delta * (e.clientX / this.chartV.width);
    b.sessionVariables.newViewportMaximum = b.viewportMaximum + delta * (1 - e.clientX / this.chartV.width);
    this.chartV.render();
    }