DEV Community

Michael Vestergaard
Michael Vestergaard

Posted on

Using lerp and damp in javascript

Almost every project I do as a creative developer utilizes linear interpolation - also called "lerp". It's a simple way of easing from position A to B. Without diving into the math, there's another approach called damp (or smoothdamp), this is almost similar but has a smoother curve (more like a Quad and less like an Expo).

The classic way of using lerp is like this:

//speed between 0-1
_tweenedValue += (_actualValue - _tweenedValue) * _speed;
Enter fullscreen mode Exit fullscreen mode

This works very well. You can even tween the speed if you want the movement to start slowly:

_this._speed = 0;
gsap.to(_this, 1, {_speed:.2, ease:"linear"});
_tweenedValue += (_actualValue - _tweenedValue) * _this._speed;
Enter fullscreen mode Exit fullscreen mode

I'm using the above in custom cursors, carousels, elements that move based on mouse position and even for a smooth pagescroller (similar to Lenis).

Below is an example of both lerp and damp (blue and red), but also a fun little bouncy/elastic approach (green):

Top comments (0)