Skip to content

Instantly share code, notes, and snippets.

@nikolas
Forked from rosszurowski/lerp-color.js
Last active June 29, 2023 14:12
Show Gist options
  • Save nikolas/b0cce2261f1382159b507dd492e1ceef to your computer and use it in GitHub Desktop.
Save nikolas/b0cce2261f1382159b507dd492e1ceef to your computer and use it in GitHub Desktop.
Linear interpolation for hexadecimal colors.
/**
* A linear interpolator for hex colors.
*
* Based on:
* https://gist.github.com/rosszurowski/67f04465c424a9bc0dae
*
* @param {Number} a (hex color start val)
* @param {Number} b (hex color end val)
* @param {Number} amount (the amount to fade from a to b)
*
* @example
* // returns 0x7f7f7f
* lerpColor(0x000000, 0xffffff, 0.5)
*
* @returns {Number}
*/
const lerpColor = function(a, b, amount) {
const ar = a >> 16,
ag = a >> 8 & 0xff,
ab = a & 0xff,
br = b >> 16,
bg = b >> 8 & 0xff,
bb = b & 0xff,
rr = ar + amount * (br - ar),
rg = ag + amount * (bg - ag),
rb = ab + amount * (bb - ab);
return (rr << 16) + (rg << 8) + (rb | 0);
};
@kulture
Copy link

kulture commented Jul 25, 2022

Thanks! This was helpful. I used the following to return a CSS-readable string:

return `#${((rr << 16) + (rg << 8) + (rb | 0)).toString(16).padStart(6, '0').slice(-6)}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment