Linear interpolation (sometimes called 'lerp' or 'mix') is a really handy function for creative coding, game development and generative art.

The function interpolates within the range [start..end] based on a 't' parameter, where 't' is typically within a [0..1] range.

For example, divide 'loop time' by 'loop duration' and you get a 't' value between 0.0 and 1.0.

Now you can map this 't' value to a new range, such as `lerp(20, 50, t)` to gradually increase a circle's radius, or `lerp(20, 10, t)` to gradually decrease its line thickness.

Another example: you can use linear interpolation to smoothly animate from one coordinate to another. Define a start point (x1, y1) and end point (x2, y2), then interpolate the 'x' and 'y' dimensions separately to find the computed point in between.

Or use linear interpolation to spring toward a moving target. Each frame, interpolate from the current value to the target value with a small 't' parameter, such as 0.05.

It's like saying: walk 5% toward the target each frame.

A more advanced example, but built on the same concept, is interpolating from one color (red) to another (blue).

To do this, we interpolate the (R, G, B) or (H, S, L) channels of the color individually, just like we would with a 2D or 3D coordinate.

Another quick example is to choose a random point along a line segment.

There are lots of ways to use linear interpolation, and lots more types of interpolation (cubic, bilinear, etc). These concepts also lead nicely into areas like: curves, splines and parametric equations.

Source code for each of these examples is available here: https://gist.github.com/mattdesl/3675c85a72075557dbb6b9e3e04a53d9

About the author:

Matt DesLauriers is a creative coder and generative artist based in London. He combines code and emergent systems to make art for the web, print media, and physical installations.

Note:

This brief introduction to lerp was originally published as a Twitter thread and is republished here with the kind permission of the original author.

[Wayback Machine Archive]