Created
August 25, 2019 15:22
-
-
Save AlphaNerd/ecdbfe9a22bbc99b4d23d1aa313a17c1 to your computer and use it in GitHub Desktop.
A basic script to help calculate the average color between 2 supplied RGB values
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// get the average color of two rgb colors. | |
function avgcolor(color1,color2){ | |
/// declare vars | |
let avg, | |
hex16,ch16, | |
hex1,hex2, | |
r,g,b, | |
res; | |
// get average of channel hex | |
avg = function(a,b){ | |
return (a+b)/2; | |
} | |
// convert to 16 bit hex | |
hex16 = function(c){ | |
return parseInt((''+c).replace('#',''),16); // ie. 2923191 or 16099355 | |
} | |
// hex component conversion | |
ch16 = function(c){ | |
var t = (c>>0).toString(16); | |
return t.length == 2 ? t : '0' + t; // ensure there are at least 2 digit | |
} | |
/// container for hex values | |
hex1 = hex16(color1); // hex value 1 | |
hex2 = hex16(color2); // hex value 2 | |
// return Rgb component of hex value | |
r = function(hex){ | |
return hex >> 16 & 0xFF; | |
} | |
// return rGb component of hex value | |
g = function(hex){ | |
return hex >> 8 & 0xFF; | |
} | |
// return rgB component of hex value | |
b = function(hex){ | |
return hex & 0xFF; | |
} | |
// compile back to rgb | |
res = '#' + ch16(avg(r(hex1),r(hex2))) + ch16(avg(g(hex1),g(hex2))) + ch16(avg(b(hex1),b(hex2))); | |
return res; // return resulting rgb average | |
} | |
console.log(avgcolor('#2c9ab7','#f5a81b')); // "#90a169" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment