Skip to content

Interpolation

Interpolation (also known as lerping or tweening) allows us to generate any value within a range. The start of the range is A, the end of the range B.

To interpolate between A & B, we also need an amount. This determines what point along the range to calculate. Amount is expressed as a scalar percentange (0..1).

Here’s an example of interpolating a range of 1024-2310:

A from-scratch implementation of interpolation is as simple as this:

// Interpolate from a->b by amount (0..1)
const interpolate = (amount, a, b) => (1-amount) * a + amount * b;
interpolate(0.5, 1024, 2310);

ixfx has interpolate in the Module Numbers module. This include a bunch of additional ‘nice to have’ features beyond the simple implementation above.

import { interpolate } from "https://unpkg.com/ixfx/dist/numbers.js";
// Returns the value 50% between 1024 and 2310 (ie. 1667)
interpolate(0.5, 1024, 2310);

Where interpolation really gets useful is interpolating over time. To do this, we might want to repeatedly call interpolate, but vary amount over time. We can see this in action on the next page.

Interpolating points

The examples so far have been simple - calculating a value between two numbers. But the same concept can be applied to richer data such as Points.

A practical use of interpolation to move an element from its current location to where the user taps. Below we use Points.interpolate to interpolate { x, y } values.

import { Points } from "https://unpkg.com/ixfx/dist/geometry.js";
Points.interpolate(amount, startPos, targetPos);

In the below example we interpolate from { x: 0.1, y: 0.1} to { x: 0.8, y: 0.9 }.