An ES6 version with comprehensions:
function interpolateColor(c0, c1, f){
c0 = c0.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * (1-f))
c1 = c1.match(/.{1,2}/g).map((oct)=>parseInt(oct, 16) * f)
let ci = [0,1,2].map(i => Math.min(Math.round(c0[i]+c1[i]), 255))
return ci.reduce((a,v) => ((a << 8) + v), 0).toString(16).padStart(6, "0")
}
As in the accepted answer, c0
,c1
are color codes (without the leading #
) and f
is "progress" between the two values. (At f=0
this ends up returning c0
, at f=1
this returns c1
).
- The first two lines convert the color codes into arrays of scaled integers
- The third line:
- "zips" the two integer arrays
- sums the corresponding values
- rounds the sum and clamps it to 0-255
- The fourth line:
- converts the integer array into a single integer (reduce and bitshifting)
- converts the integer into its hexadecimal string form
- ensures the resulting string is 6 characters long and returns it