Skip to content

Instantly share code, notes, and snippets.

@alexgrozav
Last active September 24, 2017 19:54
Show Gist options
  • Save alexgrozav/e104349ddbe56218705ce3467c0becf0 to your computer and use it in GitHub Desktop.
Save alexgrozav/e104349ddbe56218705ce3467c0becf0 to your computer and use it in GitHub Desktop.
A simple Stylus function for getting the contrasting text color (black or white) based on the background color. Extracted from Inkline framework https://github.com/inkline/inkline.
/**
* Get contrast text color for a background color by calculating the luminance
* of the given input color.
*
* @param color Text background color
* @return Contrasting text color
*/
contrastColor(color)
RGB = {
r: red(color)
g: green(color)
b: blue(color)
}
for k, c in RGB
c = c / 255.0
if c <= 0.03928
c = c / 12.92
else
c = ((c + 0.055) / 1.055) ** 2.4
RGB[k] = c
L = 0.2126 * RGB.r + 0.7152 * RGB.g + 0.0722 * RGB.b
if L > 0.179
return #000000
else
return #ffffff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment