Created
July 23, 2020 23:18
-
-
Save nihlton/2c0fe0c57d13c126b1574b1da7c95528 to your computer and use it in GitHub Desktop.
get the color (black or white) with the best contrast for the given 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
export const getContrastColor = function (bgColor) { | |
var color = (bgColor.charAt(0) === '#') ? bgColor.substring(1, 7) : bgColor | |
var r = parseInt(color.substring(0, 2), 16) // hexToR | |
var g = parseInt(color.substring(2, 4), 16) // hexToG | |
var b = parseInt(color.substring(4, 6), 16) // hexToB | |
var uiColors = [r / 255, g / 255, b / 255] | |
var c = uiColors.map((col) => { | |
if (col <= 0.03928) { return col / 12.92 } | |
return Math.pow((col + 0.055) / 1.055, 2.4) | |
}) | |
var L = (0.2126 * c[0]) + (0.7152 * c[1]) + (0.0722 * c[2]) | |
return (L > 0.3) ? '#000000' : '#FFFFFF' | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
demo: https://codesandbox.io/s/mfhtp
tuned slightly to match chrome's theme color contrast selection.