Created
June 29, 2023 00:47
-
-
Save NerdyDeedsLLC/9670a886563d1a24558037952896f052 to your computer and use it in GitHub Desktop.
Lightweight function that will return the appropriate foreground color (white or black) when given a HEX/HEXA background color.
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
/** | |
contrastingColor(hex, factorAlpha) | |
@Description Accepts a HEX/HEXA color in any valid format (#HEX/#HEXA/#HHEEXX/#HHEEXXAA; | |
'#' is optional), and a boolean indicating if its opacity should be | |
considered and returns either '#000' or '#FFF' representing the preferred | |
foreground color for text atop it. | |
@param <STRING> hex any valid hex color code. | |
@param <BOOLEAN> factorAlpha whether or opacity should be considered (DEFAULT: false) | |
@returns <STRING> returns hex color code for white or black (#FFF/#000) | |
*/ | |
function contrastingColor(hex, factorAlpha=false) { | |
let [r,g,b,a]=hex.replace(/^#?(?:(?:(..)(..)(..)(..)?)|(?:(.)(.)(.)(.)?))$/, '$1$5$5$2$6$6$3$7$7$4$8$8').match(/(..)/g).map(rgb=>parseInt('0x'+rgb)); | |
return ((~~(r*299) + ~~(g*587) + ~~(b*114))/1000) >= 128 || (!!(~(128/a) + 1) && factorAlpha) ? '#000' : '#FFF'; | |
} |
Author
NerdyDeedsLLC
commented
Jun 29, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment