Ahhhhhhhhhhh I'm blogging again on CodePen! It's been a little while, my bad.

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. I also employed this technique for a parallax scrolling example for a previous blog post.

So, the lerp "trick" is a great tool to have up our web animation sleeves to combat linear or jagged movement. If you have used or do use lerp in your CodePens be sure to share your examples with us in the comments below!

Your questions and suggestions give me ideas for what to write about next! So if you have any questions please comment below, send me a tweet @rachsmithtweets, submit to my AMA, or flick me an email at contact at rachsmith dot com.