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.
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.
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".
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.
Top comments (0)