Skip to content

Instantly share code, notes, and snippets.

@nihlton
Created July 23, 2020 23:18
Show Gist options
  • Save nihlton/2c0fe0c57d13c126b1574b1da7c95528 to your computer and use it in GitHub Desktop.
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.
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'
}
@nihlton
Copy link
Author

nihlton commented Jul 23, 2020

demo: https://codesandbox.io/s/mfhtp

tuned slightly to match chrome's theme color contrast selection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment