Lerp: Linear Interpolation Function
I have found the lerp function to be really useful when creating animation to make things transition smoothly.
function lerp(start, end, t) {
return (1 - t) * start + t * end;
}
Many demo can be created from this, but for now here's a example how to transition between 2 colors in Canvas.
Full demo code:
const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
function lerp(start, end, t) {
return (1 - t) * start + t * end;
}
function lerpColor(from, to, t)
{
var color = {r:0, g: 0, b: 0};
color.r = lerp(from.r, to.r, t);
color.g = lerp(from.g, to.g, t);
color.b = lerp(from.b, to.b, t);
return color;
}
var now, last, t;
var duration = 2000;
var current = 0;
var colorA = {
r: 0,
g: 250,
b: 250
};
var colorB = {
r: 255,
g: 0,
b: 255,
};
function draw() {
context.clearRect(0, 0, canvas.width, canvas.height);
now = performance.now();
var dt = now - last;
current += dt;
last = now;
t = current/duration;
if (current>duration) {
t = 0;
current = 0;
var c = colorA;
colorA = colorB;
colorB = c;
}
var CC = lerpColor(colorA, colorB, current/duration);
context.fillStyle = `rgba(${CC.r}, ${CC.g}, ${CC.b}, 1.0)`;
context.fillRect(0, 0, canvas.width, canvas.height);
context.restore();
window.requestAnimationFrame(draw);
}
// start
last = performance.now();
window.requestAnimationFrame(draw);