Lerp
When CodePen blogs were a thing I added a bunch of posts to mine. Some of the content still holds up in 2023 so I decided to repost my favourites on this site.
Today I want to talk about a little animation trick that I use all the time called lerp. Lerp is the nickname for Linear Interpolation between two points. It’s a fairly simple effect to implement but can really improve the look of your animations if you’re moving an object from a point A to point B.
How does it work?
Given you have a current position for an object, and a position you want to move that object towards - you can linearly interpolate to a percentage of the distance between those points, and update the position by that amount on each frame.
// to run on each frame
function lerp(position, targetPosition) {
// update position by 20% of the distance between position and target position
position.x += (targetPosition.x - position.x)*0.2;
position.y += (targetPosition.y - position.y)*0.2;
}
By doing this, the amount the object moves becomes smaller as the distance between position and target decreases. This means the object will slow down as it gets closer to its target, creating a nice easing effect.
Lerp in action - some examples
Here is an example of a ball following the user’s mouse or touch. If we make the ball move to the place the mouse is as soon as it moves, the ball movement can be very fast and/or disjointed. We might also be able to see separate “ball frames” if we move our mouse really fast.
See the Pen Follow the mouse - no lerp by Rachel Smith (@rachsmith) on CodePen.
Here’s the same demo, except this time we’re using lerp. Instead of moving the ball right to the mouse position, we’ll move it 10% of the distance towards that position on each frame.
See the Pen Follow the mouse - with lerp by Rachel Smith (@rachsmith) on CodePen.
Notice the ball movement is a lot smoother and an overall more pleasing effect.
Here’s another example of using lerp. This time we’ve got a scrolling indicator that updates as you scroll down the “page”.
See the Pen Scrolling - no lerp by Rachel Smith (@rachsmith) on CodePen.
See the Pen Scrolling - with lerp by Rachel Smith (@rachsmith) on CodePen.
If we add lerp to this example we’re lerping the indicator towards the scroll percentage instead of pointing it at the actual position - this smoothes out the movement of the indicator.
So, the lerp “trick” is a great tool to have up our web animation sleeves to combat linear or jagged movement.
Thanks for reading! If you'd like to share your thoughts you can leave a comment, send me an email, Tweet at me, or add an issue on GitHub.
Comments
The Comments system is powered by a third party service - Talkyard. Sometimes they don't load 😞. If you're having trouble leaving a comment you can send me an email.