Search code examples
mathcanvaszooming

Linear zoom function 2D


I have a canvas and a scale value. The maximum scale is 1, the minimum scale value is something like 0.1 or above. Let’s say we have discrete time units. I’m looking for a function that zooms linear over an time interval I (lets say 100 time units), from a start zoom s to an end zoom e. Let 0 >= i < I be the current interval.

Example: Zoom from 0.2 to 1.0 in 100 time units.

Obviously zoom(i) = (e-s)/I * i does not produce a linear zoom. Because a step from 0.2 to 0.4 doubles the zoom, while the same amount from 0.8 to 1.0 only increases the zoom by 25%.

I was thinking that this function needs something logarithmic to base 2, but I’m stuck finding the right function.


Solution

  • To provide constant ratio with constant argument difference, you need exponential function (it is possible to use any base, e, 2, 10 and so on with corresponding logarithms)

    F(x) = A * Exp(B * x)
    

    To get coefficients A and B for given border conditions (argument x0 corresponds to function value F0):

    F0 = A * Exp(B * x0)
    F1 = A * Exp(B * x1)
    

    divide the second equation by the first:

    Exp(B * (x1 -x0) = F1 / F0
    B * (x1 -x0) = ln(F1 / F0)
    

    so

    B = ln(F1 / F0) / (x1 - x0)
    

    and

    A = F0 * Exp(-B * x0)
    

    For your example

    x0=0, x1=100
    zoom0 = 0.2, zoom1=1
    B = ln(5) / 100 = 0.0161
    A = 0.2 * Exp(0) = 0.2
    zoom(i) = 0.2 * Exp(0.0161 * i)
    
    zoom(0) = 0.2
    zoom(50) = 0.447
    zoom(100) = 1
    
    note that 
    zoom(50) / zoom(0) = zoom(100) / zoom(50)