Skip to content

Instantly share code, notes, and snippets.

@Gerhut
Created August 24, 2021 07:58
Show Gist options
  • Save Gerhut/a0972b343d5e5b7ba30571bcc1642c56 to your computer and use it in GitHub Desktop.
Save Gerhut/a0972b343d5e5b7ba30571bcc1642c56 to your computer and use it in GitHub Desktop.
/**
* @callback Tween
* @param {number} x
* @returns {number}
*/
/**
* @callback Easing
* @param {number} x
* @returns {number}
*/
/**
* @param {Easing} [easing]
* @returns {Tween}
*/
export default function createTween(x0 = 0, x1 = 1, y0 = 0, y1 = 1, easing) {
const k = (y1 - y0) / (x1 - x0)
const b = (x1 * y0 - x0 * y1) / (x1 - x0)
if (easing !== undefined) {
const dx = x1 - x0
return (x) => {
if (x <= x0) return y0
if (x >= x1) return y1
x = easing((x - x0) / dx) * dx + x0
return k * x + b
}
}
return (x) => {
if (x <= x0) return y0
if (x >= x1) return y1
return k * x + b
}
}
// Paste more easings from https://easings.net/
/** @type {Easing} */
export const easeInExpo = (x) => (x === 0 ? 0 : Math.pow(2, 10 * x - 10))
/** @type {Easing} */
export const easeOutExpo = (x) => (x === 1 ? 1 : 1 - Math.pow(2, -10 * x))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment