Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Last active December 31, 2015 17:09
Show Gist options
  • Save Munawwar/8018166 to your computer and use it in GitHub Desktop.
Save Munawwar/8018166 to your computer and use it in GitHub Desktop.
Two functions: i. To find contrast (actually luma) ratio of two colors. ii. To find contrast grey shade of any color.
/* Taken from http://stackoverflow.com/a/13558570.
* aka inverse gamma. Some call it "inverse sRGB companding".
* All the constants are taken from sRGB spec.
* Read about it at http://en.wikipedia.org/wiki/SRGB (I didn't understand how they derived the approximation).
*/
function linear(R) { //in sRGB as hex string
var s = parseInt(R, 16) / 255;
if (s <= 0.04045) {
return s / 12.92;
} else {
return Math.pow((s + 0.055) / 1.055, 2.4);
}
}
function nonLinear(v) {
if (v <= 0.0031308) {
v *= 12.92;
} else {
v = 1.055 * Math.pow(v, 1/2.4) - 0.055;
}
return v * 255;
}
//Luma (http://en.wikipedia.org/wiki/Luma_%28video%29). Which is also the 'Y' from YUV color space.
function Luminance(R, G, B) { //sRGB, each as hex string
return 0.2126 * linear(R) +
0.7152 * linear(G) +
0.0722 * linear(B);
}
function getContrastRatio(RGB1, RGB2) {
var L1 = Luminance(RGB1.substr(1,2), RGB1.substr(3,2), RGB1.substr(5,2)),
L2 = Luminance(RGB2.substr(1,2), RGB2.substr(3,2), RGB2.substr(5,2)),
LMax = Math.max(L1, L2),
LMin = Math.min(L1, L2);
return (LMax + 0.05) / (LMin + 0.05);
}
//http://juicystudio.com/article/luminositycontrastratioalgorithm.php#ratiosamples
//Luminosity Constrast Ratio algorithm, developed by Gregg Vanderheiden, Dave Kelso, and Aries Arditi
//suggests that ratio should be = 3 for large text and ratio = 5 for small text.
function findContrastShade(RGB, ratio) {
var L = Luminance(RGB.substr(1,2), RGB.substr(3,2), RGB.substr(5,2)),
LMax = (L + 0.05) * (ratio || 5) - 0.05,
LMin = (L + 0.05) / (ratio || 5) - 0.05,
//Assume R=G=B
R = (LMax > 0 && LMax < 1) ? LMax : LMin,
hex = Math.round(nonLinear(R)).toString(16);
return '#' + (new Array(4)).join((hex.length < 2 ? '0' : '') + hex);
}
getContrastRatio('#4080FF', '#808080');
getContrastRatio('#4080FF', '#FFFFFF');
findContrastShade('#4080FF');
@Munawwar
Copy link
Author

Update: Fixed findContrastShade() to prepend '0' to single digit hex numbers. Also prefix color with '#' (like CSS).

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