TExcelTAD
Home › 2D Games with JavaScript & Canvas › Tweening & Easing

Tweening & Easing

A tween (from "in-between") changes a value from a start to an end over a fixed time: a menu sliding in, a coin flying to the score counter, a door opening, a "+100" popping up. An easing function decides how the value travels: at constant speed, starting slow, overshooting and settling back. Good easing is the difference between UI that feels mechanical and UI that feels alive.

Lerp and easing functions

Everything starts with linear interpolation:

js
const lerp = (a, b, k) => a + (b - a) * k;   // k = 0 gives a, k = 1 gives b

A tween computes the progress t = elapsed / duration (0 to 1), passes it through an easing function and uses the result as k. An easing function maps 0 to 0 and 1 to 1, and bends what happens in between:

js · try it yourself
const ease = {
  linear: (t) => t,
  inQuad: (t) => t * t,
  outQuad: (t) => 1 - (1 - t) * (1 - t),
  inOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2),
  outBack: (t) => {
    const c1 = 1.70158, c3 = c1 + 1;
    return 1 + c3 * Math.pow(t - 1, 3) + c1 * Math.pow(t - 1, 2);
  },
  outBounce: (t) => {
    const n = 7.5625, d = 2.75;
    if (t < 1 / d) return n * t * t;
    if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75;
    if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375;
    return n * (t -= 2.625 / d) * t + 0.984375;
  },
};

const fmt = (v) => (Math.abs(v) < 5e-4 ? 0 : v).toFixed(3).padStart(6);
console.log('t:          ', [0, 0.25, 0.5, 0.75, 1].map(fmt).join(' '));
for (const [name, fn] of Object.entries(ease)) {
  console.log(name.padEnd(12), [0, 0.25, 0.5, 0.75, 1].map((t) => fmt(fn(t))).join(' '));
}
t:            0.000  0.250  0.500  0.750  1.000
linear        0.000  0.250  0.500  0.750  1.000
inQuad        0.000  0.063  0.250  0.563  1.000
outQuad       0.000  0.438  0.750  0.938  1.000
inOutCubic    0.000  0.063  0.500  0.938  1.000
outBack       0.000  0.817  1.088  1.064  1.000
outBounce     0.000  0.473  0.766  0.973  1.000

Read the rows like a graph. inQuad starts slow (0.063 at a quarter) and speeds up; outQuad is the opposite, fast at first and gently arriving, which is the best default for UI. outBack goes above 1 before settling: an overshoot that makes buttons and pop-ups feel springy.

Easing Feels like Typical use
outQuad / outCubic Quick start, soft landing Menus sliding in, camera moves
inQuad Accelerating Things leaving the screen, falling
inOutCubic Smooth start and stop Cut-scene cameras, platforms
outBack Overshoot and settle Pop-ups, score "pop", item pickups
outBounce Drops and bounces Falling UI, playful titles

A tiny tween runner

A tween stores its target object, start values, end values, duration and easing. A runner updates all active tweens each step and removes finished ones. Callbacks (onDone) let you chain tweens: move, then grow.

js · try it yourself
const outQuad = (t) => 1 - (1 - t) * (1 - t);

class Tweens {
  constructor() { this.list = []; }
  to(target, props, duration, easing = outQuad, onDone) {
    const from = {};
    for (const k in props) from[k] = target[k];
    this.list.push({ target, from, props, duration, easing, t: 0, onDone });
  }
  update(dt) {
    for (const tw of this.list) {
      tw.t = Math.min(tw.t + dt, tw.duration);
      const k = tw.easing(tw.t / tw.duration);
      for (const p in tw.props) tw.target[p] = tw.from[p] + (tw.props[p] - tw.from[p]) * k;
    }
    const done = this.list.filter((tw) => tw.t >= tw.duration);
    this.list = this.list.filter((tw) => tw.t < tw.duration);
    for (const tw of done) tw.onDone?.();   // may start new tweens
  }
}

const tweens = new Tweens();
const coin = { x: 0, scale: 1 };
tweens.to(coin, { x: 100 }, 0.5, outQuad, () => {
  console.log('arrived, now pop');
  tweens.to(coin, { scale: 2 }, 0.25, (t) => t);
});

for (let step = 1; step <= 6; step++) {
  tweens.update(0.125);
  console.log(`step ${step}: x=${coin.x.toFixed(2)} scale=${coin.scale.toFixed(2)} active=${tweens.list.length}`);
}
step 1: x=43.75 scale=1.00 active=1
step 2: x=75.00 scale=1.00 active=1
step 3: x=93.75 scale=1.00 active=1
arrived, now pop
step 4: x=100.00 scale=1.00 active=1
step 5: x=100.00 scale=1.50 active=1
step 6: x=100.00 scale=2.00 active=0

The step size is 0.125 s, an exact binary fraction, so the tween ends on exactly 0.5 s without floating-point drift.

Smoothing towards a moving target

A tween needs a fixed end point. For a value that chases a moving target (a camera following the player, a health bar catching up) use exponential smoothing. The tempting version x += (target - x) * 0.1 per frame depends on the frame rate: at 120 FPS it moves twice as fast as at 60 FPS. The frame-rate-independent form uses dt:

js · try it yourself
function chase(fps, frames, frameIndependent) {
  let x = 0;
  const dt = 1 / fps;
  for (let i = 0; i < frames; i++) {
    const k = frameIndependent ? 1 - Math.exp(-6 * dt) : 0.1;
    x += (100 - x) * k;
  }
  return x.toFixed(1);
}
console.log('after 0.5 s, constant 0.1:   30 FPS', chase(30, 15, false), ' 60 FPS', chase(60, 30, false));
console.log('after 0.5 s, 1 - exp(-6*dt): 30 FPS', chase(30, 15, true), ' 60 FPS', chase(60, 30, true));
after 0.5 s, constant 0.1:   30 FPS 79.4  60 FPS 95.8
after 0.5 s, 1 - exp(-6*dt): 30 FPS 95.0  60 FPS 95.0

The constant factor gives very different results; the exp version lands on the same value at any frame rate.

Playable demo

Each row uses a different easing to cross the screen and back. Press Space to make the score "pop" with outBack and to restart the race.

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
  canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set();   // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
  ctx.save();
  ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
  ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
  ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
  ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
  ctx.restore();
}
function run(update, draw, help = '') {
  const STEP = 1 / 60;
  let acc = 0, last = performance.now();
  requestAnimationFrame(function frame(now) {
    const dt = Math.min((now - last) / 1000, 0.1);
    last = now;
    if (active) {
      acc += dt;
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
      draw();
    } else if (!idleDrawn) {
      draw(); banner('Click to play', help); idleDrawn = true;
    }
    requestAnimationFrame(frame);
  });
}
// ---- end of play kit ----

const ease = {
  linear: (t) => t,
  inQuad: (t) => t * t,
  outQuad: (t) => 1 - (1 - t) * (1 - t),
  inOutCubic: (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2),
  outBack: (t) => 1 + 2.70158 * Math.pow(t - 1, 3) + 1.70158 * Math.pow(t - 1, 2),
  outBounce: (t) => {
    const n = 7.5625, d = 2.75;
    if (t < 1 / d) return n * t * t;
    if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75;
    if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375;
    return n * (t -= 2.625 / d) * t + 0.984375;
  },
};
const names = Object.keys(ease);
const DURATION = 1.4;
let time = 0, score = 0, pop = 1, popT = 1;

function update(dt) {
  time += dt;
  if (pressed.has('Space')) { time = 0; score += 100; popT = 0; }
  popT = Math.min(1, popT + dt / 0.35);
  pop = 1 + 0.8 * (1 - ease.outBack(popT));   // big at first, settles to 1 with a small undershoot
}

function draw() {
  ctx.fillStyle = '#0e1018';
  ctx.fillRect(0, 0, W, H);
  const cycle = time % (DURATION * 2);
  const forward = cycle < DURATION;
  const t = (forward ? cycle : cycle - DURATION) / DURATION;
  ctx.font = '12px monospace';
  ctx.textAlign = 'left';
  names.forEach((name, i) => {
    const y = 50 + i * 34;
    const k = ease[name](t);
    const x = forward ? 110 + k * 330 : 440 - k * 330;
    ctx.fillStyle = '#2c3350';
    ctx.fillRect(110, y + 6, 346, 2);
    ctx.fillStyle = '#9fa8da';
    ctx.fillText(name, 8, y + 11);
    ctx.fillStyle = `hsl(${i * 55} 80% 60%)`;
    ctx.fillRect(Math.round(x), y, 16, 16);
  });
  ctx.save();
  ctx.translate(W / 2, 22);
  ctx.scale(pop, pop);
  ctx.fillStyle = '#ffd54f';
  ctx.font = 'bold 18px system-ui, sans-serif';
  ctx.textAlign = 'center';
  ctx.textBaseline = 'middle';
  ctx.fillText(`SCORE ${score}`, 0, 0);
  ctx.restore();
}

run(update, draw, 'Space: score pop + restart');
</script>

Tip: Libraries such as GSAP, tween.js and the tween systems built into Phaser and Kaplay do exactly this, plus timelines, delays, yoyo and repeat. The idea underneath is always progress → easing → lerp.

Note: Easing functions above follow the widely used formulas popularised by Robert Penner; easings.net shows a curve for each.

Test yourself

What does an easing function receive and return?

  1. Pixels in, pixels out
  2. Progress from 0 to 1 in, an eased progress (0 at the start, 1 at the end) out
  3. Milliseconds in, frames out
  4. A colour in, a colour out

Which easing overshoots its target before settling?

  1. linear
  2. inQuad
  3. outBack
  4. inOutCubic

Why is x += (target - x) * 0.1 every frame a problem?

  1. It never moves
  2. It depends on the frame rate: faster screens chase faster
  3. It always overshoots
  4. It only works with integers