在CanvasJS中使用滚轮进行缩放

时间:2015-06-07 17:39:44

标签: javascript jquery html canvasjs

我正在使用此脚本绘制折线图:

  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();
    }

当前代码在鼠标单击并拖动区域时进行缩放。如何更改它以便我可以使用滚轮进行缩放?

1 个答案:

答案 0 :(得分:1)

请注意以下内容使用CanvasJS中未记录的内部文件,以后可能会中断。

  1. 附加鼠标滚轮事件处理程序:

    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. 实现处理程序

    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();
    }