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
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • 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);
};
@TheoSabattie
Copy link

Fix:

const lerpColor = function(pFrom:number, pTo:number, pRatio:number) {
    const ar = (pFrom & 0xFF0000) >> 16,
          ag = (pFrom & 0x00FF00) >> 8,
          ab = (pFrom & 0x0000FF),

          br = (pTo & 0xFF0000) >> 16,
          bg = (pTo & 0x00FF00) >> 8,
          bb = (pTo & 0x0000FF),

          rr = ar + pRatio * (br - ar),
          rg = ag + pRatio * (bg - ag),
          rb = ab + pRatio * (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