Search code examples
svgd3.jszooming

Avoid unzooming/zooming transition while updating zoom on d3


I want to programmatically translate a zoomable bar chart.
We can achieve this like presented on this example, which results in the following effect when zooming:

enter image description here

However, I would like to avoid the unzooming/zooming while the transition is translating the chart.

In other words, I would like to preserve the current zoom scale during the entire transition duration.

How can I achieve this with d3 ?


Solution

  • D3's zoom interpolation/tweening uses a special interpolator when transitioning between zoom states. This behavior can be unwanted, especially as it may not be expected.

    In your case, you can simply override the default zoom interpolator by specifying a zoom interpolator with zoom.interpolate():

    If interpolate is specified, sets the interpolation factory for zoom transitions to the specified function. If interpolate is not specified, returns the current interpolation factory, which defaults to d3.interpolateZoom to implement smooth zooming. To apply direct interpolation between two views, try d3.interpolate instead. (docs)

    So, we can replace the default interpolator with d3.interpolate. As a result, this would be your zoom behaviour:

    d3.zoom()
      .interpolate(d3.interpolate)
      ...
    

    Which will interpolate between corresponding values contained in the starting and final transform, as the scale value does not change in the translate, the scale value will not change throughout the interpolation.