Home Forums Chart Support Useing CanvasJS with mousewheel

Useing CanvasJS with mousewheel

Viewing 5 posts - 1 through 5 (of 5 total)
  • #23355

    Do you have any examples or recommendations for using CanvasJS charts (in particular zoom in) from mouse wheel?

    Same question for keyboard keys interaction with the plots.

    Thanks

    #23356

    @mihaela,

    You can zoom the chart using mousewheel by attaching wheel event to the chart. Please find the code snippet below.

    document.getElementsByClassName("canvasjs-chart-canvas")[1].addEventListener("wheel", function(e){
      e.preventDefault();
      
      if(e.clientX < chart.plotArea.x1 || e.clientX > chart.plotArea.x2 || e.clientY < chart.plotArea.y1 || e.clientY > chart.plotArea.y2)
      	return;
        
      var axisX = chart.axisX[0];
      var viewportMin = axisX.get("viewportMinimum"),
          viewportMax = axisX.get("viewportMaximum"),
          interval = axisX.get("minimum");
    
      var newViewportMin, newViewportMax;
    
      if (e.deltaY < 0) {
        newViewportMin = viewportMin + interval;
        newViewportMax = viewportMax - interval;
      }
      else if (e.deltaY > 0) {
        newViewportMin = viewportMin - interval;
        newViewportMax = viewportMax + interval;
      }
    
      if(newViewportMin >= chart.axisX[0].get("minimum") && newViewportMax <= chart.axisX[0].get("maximum") && (newViewportMax - newViewportMin) > (2 * interval)){
        chart.axisX[0].set("viewportMinimum", newViewportMin, false);
        chart.axisX[0].set("viewportMaximum", newViewportMax);
      }
    
    });

    Please take a look at this JSFiddle for complete code.
    Zooming chart using mouse wheel


    Vishwas R
    Team CanvasJS

    #23371

    Great example, exactly as needed, thanks!

    Is there an example you can provide for attaching keyboard events? We would like to use keyboard keys as shortcuts for certain operations like zoom in/out or pan left right.

    Thanks again for your excellent support.

    #23374

    @mihaela,

    Similar to how wheel event was attached to achieve zooming the chart with mouse-wheel, you need to attach keydown event to achieve on pressing any key in the keyboard. Please take a look at this JSFiddle. Please refer this stackoverflow thread for more information on key-codes.

    Note: As JSFiddle has multiple panels (like HTML, JS, Result, etc), make sure you click somewhere in the result panel and then on top of chart once so that keyboard events are captured by chart.


    Vishwas R
    Team CanvasJS

    #23380

    Thanks for the example, it is working great.

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.