Last active
January 5, 2017 21:20
-
-
Save ameliabradley/c967b0c2d896abef66c74ed14a170169 to your computer and use it in GitHub Desktop.
Given a hex color, finds the optimal font color (black or white)
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
function getFontColorFromBackgroundColor (bgColor) { | |
if (!bgColor.match(/#[0-9a-z]{6}/i)) { | |
return 'white'; | |
} | |
const [r, g, b] = [1, 3, 5].map((o) => parseInt(bgColor.slice(o, o + 2), 16)); | |
const greyscale = (0.2125 * r) + (0.7154 * g) + (0.0721 * b); | |
return (greyscale > 127) ? 'black' : 'white'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JavaScript function that takes any background color and produces the most readable, legible font color.
Inspired by Mark Ransom's answer on StackOverflow.