Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple easing function in javascript

I'm having trouble figuring out this simple math problem. I have spent over two hours reading through various related answers on SO and Google, but it seems my high school math knowledge is gone.

On the page I have an element, that, once it passes a threshold, gets scaled down, the closer it gets to the edge of the containing element. Right now, it scales in a linear fashion. I calculate the distance to the container's edge, compare it to the threshold value (where the scale is 100%) and calculate a percentage from that, that is used to actually scale the Element (via CSS transform).

What I would like, is for the scaling to start slowly for about the first 60-80% and then ramp up considerably.

To me it seems I need some sort of inverse exponential or logarithmic function to do this, but I can't figure out exactly how to implement this. Ideally, the function would return 0.0 for x = threshold and 1.0 for x = 0 (where x would be the element's current position/percentage).

Any help is appreciated. I think this is probably trivial, but I cannot wrap my head around it.

like image 289
oelna Avatar asked Jun 08 '26 20:06

oelna


2 Answers

Here's two you could try:

(cos(pi*x) + 1) / 2

Plot on Wolfram Alpha

1 - x^2

Plot on Wolfram Alpha

Depending on if you want them to ease out or be steep at the threshold. These are normalized to (0,1), but you can easily scale them to whatever interval by dividing x by your threshold.

like image 120
cfh Avatar answered Jun 10 '26 10:06

cfh


Here you go:

function easeInOutQuad(t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
}

where

  • t is current time
  • b is start value
  • c is change in value
  • d is duration

it's all supplied from this great list of easing equations: http://gizma.com/easing/

like image 28
Emil Ingerslev Avatar answered Jun 10 '26 10:06

Emil Ingerslev