5.20203.748
5.20203.748

Zooming in FlexChart

Zooming can be easily implemented in FlexChart by taking advantage of its flexible API. The easiest solutions are to zoom by buttons or by scrolling the mouse wheel. Both approaches work by changing the min/max properties of the chart's axes.

The example below includes two methods, applyZoom and applyZoomAxis. The applyZoom method simply calls the other one for each axis. You could simply use applyZoomAxis to zoom on a single axis only. The methods require the zoom factor and the center of where you want to zoom from. The zoom factor should be <1 for zooming in, and >1 for zooming out.

// apply a zoom factor to the chart (keeping the center constant)
 function applyZoom(chart, factor, center) {
      applyZoomAxis(chart.axisX, factor, center ? center.x : null);
    applyZoomAxis(chart.axisY, factor, center ? center.y : null);
    }
 function applyZoomAxis(axis, factor, center) {
      if (!factor) { // reset
        axis.min = axis.max = null;
    } else {
        var min = (axis.min != null ? axis.min : axis.actualMin).valueOf();
      var max = (axis.max != null ? axis.max : axis.actualMax).valueOf();
      if (center == null) {
          center = (min + max) /2;
      }
      axis.min = center - (center - min) * factor;
      axis.max = center + (max - center) * factor;
    }
  }

Zooming by Mouse Wheel

Next, let's use the methods above to implement zooming by mouse wheel. The wheel zooming in this example is done around the mouse pointer rather than the center of the chart. The zoom factor is determined by whether the mouse deltaY is above or below zero.

// zoom with the mouse wheel
myChart.hostElement.addEventListener('wheel', function(e) {
  if (e.ctrlKey) {
    var center = theChart.pointToData(e.clientX, e.clientY);
      applyZoom(theChart, e.deltaY > 0 ? 1.1: .9, center);
        e.preventDefault();
    }
  })

Zooming by Buttons

You can add "Zoom In" and "Zoom Out" buttons that work by also changing the min/max properties of the chart's axes. With buttons, the chart is zoomed around the center. This example also shows how to reset the zoom by passing 'null' as the zoom factor.

// zoom logic
  document.getElementById('btnZoomIn').addEventListener('click', function () {
      applyZoom(theChart, .9)
  });
  document.getElementById('btnZoomOut').addEventListener('click', function () {
      applyZoom(theChart, 1.1)
  });
  document.getElementById('btnResetZoom').addEventListener('click', function () {
    applyZoom(theChart, null);
    });

Zooming by Dragging a Box

Another popular zooming technique is to drag a box with the mouse. This can also be implemented using FlexChart. The best way to see this is to check out the demos.