Created
January 7, 2016 13:04
-
-
Save mrpapercut/2376ec07388a108faede to your computer and use it in GitHub Desktop.
Calculate if your text is readable on a colored background for colorblind people
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
/** | |
* ColorContrast | |
* Check if your text is readable on your background for colorblind people | |
* | |
* Usage: | |
* colorContrast(foregroundColor, backgroundColor) | |
* if true, the contrast is sufficient | |
*/ | |
const hexToRgb = hex => { | |
hex = hex.toUpperCase().replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (m, r, g, b) => [r, r, g, g, b, b].join('')); | |
const res = hex.match(/^#?([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})$/); | |
return res ? { | |
r: parseInt(res[1], 16), | |
g: parseInt(res[2], 16), | |
b: parseInt(res[3], 16) | |
} : null; | |
}; | |
const getsRGB = color => (color / 255) <= 0.03928 ? color / 12.92 : Math.pow((color + 0.055) / 1.055, 2.4); | |
const getL = color => { | |
const {r, g, b} = hexToRgb(color), | |
R = getsRGB(r), | |
G = getsRGB(g), | |
B = getsRGB(b); | |
return (0.2126 * R + 0.7152 * G + 0.0722 * B); | |
}; | |
const colorContrast = (c1, c2) => { | |
const L1 = getL(c1), | |
L2 = getL(c2), | |
ratio = (Math.max(L1, L2) + 0.05) / (Math.min(L1, L2) + 0.05); | |
return ratio >= 3; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment