Raphaël Easing Equations How To
const { pow, PI } = Math;
// mostly unedited code from Raphaël
var ef = {
linear: function(n) {
return n;
},
'<': function(n) {
return pow(n, 1.7);
},
'>': function(n) {
return pow(n, 0.48);
},
'<>': function(n) {
var q = 0.48 - n / 1.04,
Q = Math.sqrt(0.1734 + q * q),
x = Q - q,
X = pow(abs(x), 1 / 3) * (x < 0 ? -1 : 1),
y = -Q - q,
Y = pow(abs(y), 1 / 3) * (y < 0 ? -1 : 1),
t = X + Y + 0.5;
return (1 - t) * 3 * t * t + t * t * t;
},
backIn: function(n) {
var s = 1.70158;
return n * n * ((s + 1) * n - s);
},
backOut: function(n) {
n = n - 1;
var s = 1.70158;
return n * n * ((s + 1) * n + s) + 1;
},
elastic: function(n) {
if (n == !!n) {
return n;
}
return pow(2, -10 * n) * Math.sin(((n - 0.075) * (2 * PI)) / 0.3) + 1;
},
bounce: function(n) {
var s = 7.5625,
p = 2.75,
l;
if (n < 1 / p) {
l = s * n * n;
} else {
if (n < 2 / p) {
n -= 1.5 / p;
l = s * n * n + 0.75;
} else {
if (n < 2.5 / p) {
n -= 2.25 / p;
l = s * n * n + 0.9375;
} else {
n -= 2.625 / p;
l = s * n * n + 0.984375;
}
}
}
return l;
}
};
ef.easeIn = ef['ease-in'] = ef['<'];
ef.easeOut = ef['ease-out'] = ef['>'];
ef.easeInOut = ef['ease-in-out'] = ef['<>'];
ef['back-in'] = ef.backIn;
ef['back-out'] = ef.backOut;
// create a dot
function dot(x, y, radius, color) {
const el = document.createElement('div');
const size = `${radius * 2}px`;
Object.assign(el.style, {
position: 'absolute',
left: `${x}px`,
top: `${y}px`,
width: size,
height: size,
transform: `translate(${-radius}px, ${-radius}px)`,
borderRadius: '50%',
background: color
});
el.classList.add('dot');
document.body.appendChild(el);
return el;
}
const elA = dot(0, 40, 30, 'red');
const elB = dot(0, 110, 30, 'blue');
const elC = dot(0, 160, 20, 'green');
// how to use the easing equations:
let t = 0;
let start = Date.now();
let time = 0;
let duration = 2; // 2 seconds
function loop() {
// frame based
elA.style.left = `${ef.elastic(t) * 50}%`;
t += 0.005;
// time based
if (time <= duration) {
time = (Date.now() - start) / 1000;
const param = time / duration;
elB.style.left = `${ef.elastic(param) * 50}%`;
// green bounce example
elC.style.left = `${ef.bounce(param) * 50}%`;
}
requestAnimationFrame(loop);
}
loop();
I realized it might not be obvious how to use Raphaël’s easing equations. So I speed coded this example.
If you’d like to learn more about this kind of thing gsap is a great place to start… it is amazing… I highly recommend browsing the source.