Last active
June 25, 2024 07:46
-
-
Save jagomf/c8ef36166badb2a533da19f4489ee742 to your computer and use it in GitHub Desktop.
Select foreground light/dark color based on background color
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
/** | |
* Selects light or dark color for foreground (mainly text) based on background color | |
* @param bgColor Background color to evaluate | |
* @param lightColor Light foreground color (defaults to white) | |
* @param darkColor Dark foreground color (defaults to black) | |
* @returns Light or dark color based on background color | |
* @see https://stackoverflow.com/a/41491220 | |
*/ | |
function pickTextColorBasedOnBgColorAdvanced(bgColor: string, lightColor = '#FFFFFF', darkColor = '#000000'): string { | |
const color = (bgColor.startsWith('#')) ? bgColor.substring(1, 7) : bgColor; | |
const r = parseInt(color.substring(0, 2), 16); // hexToR | |
const g = parseInt(color.substring(2, 4), 16); // hexToG | |
const b = parseInt(color.substring(4, 6), 16); // hexToB | |
const uicolors = [r / 255, g / 255, b / 255]; | |
const c = uicolors.map((col) => { | |
if (col <= 0.03928) { | |
return col / 12.92; | |
} | |
return Math.pow((col + 0.055) / 1.055, 2.4); | |
}); | |
const L = (0.2126 * c[0]) + (0.7152 * c[1]) + (0.0722 * c[2]); | |
return (L > 0.179) ? darkColor : lightColor; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment