Skip to content

Instantly share code, notes, and snippets.

@rosszurowski
Last active September 24, 2024 23:19
Show Gist options
  • Save rosszurowski/67f04465c424a9bc0dae to your computer and use it in GitHub Desktop.
Save rosszurowski/67f04465c424a9bc0dae to your computer and use it in GitHub Desktop.
Linear interpolation for hexadecimal colors.
/**
* A linear interpolator for hexadecimal colors
* @param {String} a
* @param {String} b
* @param {Number} amount
* @example
* // returns #7F7F7F
* lerpColor('#000000', '#ffffff', 0.5)
* @returns {String}
*/
function lerpColor(a, b, amount) {
var ah = parseInt(a.replace(/#/g, ''), 16),
ar = ah >> 16, ag = ah >> 8 & 0xff, ab = ah & 0xff,
bh = parseInt(b.replace(/#/g, ''), 16),
br = bh >> 16, bg = bh >> 8 & 0xff, bb = bh & 0xff,
rr = ar + amount * (br - ar),
rg = ag + amount * (bg - ag),
rb = ab + amount * (bb - ab);
return '#' + ((1 << 24) + (rr << 16) + (rg << 8) + rb | 0).toString(16).slice(1);
}
@skaraman
Copy link

for huge performance boost ->

ah = +a.replace('#', '0x')

bh = +b.replace('#', '0x')

@nikolas
Copy link

nikolas commented Dec 8, 2018

Yeah is the string parsing necessary? I mean, it's not like I've seen a performance problem. Anyways, here's a version that just deals with hex literals: https://gist.github.com/nikolas/b0cce2261f1382159b507dd492e1ceef

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