Created
July 17, 2019 16:32
-
-
Save viveknarang/93c542bbca118d3ddd129938791ff5b9 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* This function estimates the average of two six-digit hexadecimal colors. | |
* The function assumes that the inputs are valid. | |
* @param {*} color1 // first hexadecimal color | |
* @param {*} color2 // second hexadecimal color | |
* @author Vivek Narang | |
*/ | |
function avgColor(color1, color2) { | |
// Parse the red part of the inputs and convert them in the integer format. | |
var r1 = parseInt(color1.substring(0, 2), 16); | |
var r2 = parseInt(color2.substring(0, 2), 16); | |
// Parse the green part of the inputs and convert them in the integer format. | |
var g1 = parseInt(color1.substring(2, 4), 16); | |
var g2 = parseInt(color2.substring(2, 4), 16); | |
// Parse the blue part of the inputs and convert them in the integer format. | |
var b1 = parseInt(color1.substring(4, 6), 16); | |
var b2 = parseInt(color2.substring(4, 6), 16); | |
// Sum up the squares of the red part of the input. | |
var rsq = Math.pow(r1, 2) + Math.pow(r2, 2); | |
// Sum up the squares of the green part of the input. | |
var gsq = Math.pow(g1, 2) + Math.pow(g2, 2); | |
// Sum up the squares of the blue part of the input. | |
var bsq = Math.pow(b1, 2) + Math.pow(b2, 2); | |
// Return the Hex representation of the int casted square roots of half of the rsq, gsq & bsq variables computed above ... | |
return (parseInt(Math.sqrt(rsq/2))).toString(16) + (parseInt(Math.sqrt(gsq/2))).toString(16) + (parseInt(Math.sqrt(bsq/2))).toString(16); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment