Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Write a function that takes 2 colors as arguments and returns the average color.
- - The parameters will be two 6-digit hexadecimal strings. This does not need to be validated.
- - The return value should be a 6-digit hexadecimal string.
- - The hexadecimal strings represent colors in RGB, much like in CSS.
- - The average color is to be determined by taking the arithmetic mean for each component: red, green and blue.
- */
- function get_components(color) {
- const r_hex = color.substr(0, 2);
- const g_hex = color.substr(2, 2);
- const b_hex = color.substr(4, 2);
- return {
- r: parseInt(r_hex, 16),
- g: parseInt(g_hex, 16),
- b: parseInt(b_hex, 16),
- }
- }
- function to_hexstring(x) {
- let result = x.toString(16);
- if (x < 16) {
- result = '0' + result;
- }
- return result;
- }
- function get_blend_color(color1, color2) {
- const color1_components = get_components(color1);
- const color2_components = get_components(color2);
- const r_avg = Math.round((color1_components.r + color2_components.r) / 2);
- const g_avg = Math.round((color1_components.g + color2_components.g) / 2);
- const b_avg = Math.round((color1_components.b + color2_components.b) / 2);
- const color3 = [r_avg, g_avg, b_avg].map(to_hexstring).join('');
- return color3;
- }
- console.assert(get_blend_color('ffffff', '000000') == '808080');
- console.assert(get_blend_color('000000', 'ffffff') == '808080');
- console.assert(get_blend_color('000000', '000000') == '000000');
- console.assert(get_blend_color('ffffff', 'ffffff') == 'ffffff');
- console.assert(get_blend_color('444444', 'afafaf') == '7a7a7a');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement