Skip to content

Instantly share code, notes, and snippets.

@natecavanaugh
Created July 16, 2013 21:09
Show Gist options
  • Save natecavanaugh/6014076 to your computer and use it in GitHub Desktop.
Save natecavanaugh/6014076 to your computer and use it in GitHub Desktop.
contrast ratio calculator
// Ported from http://stackoverflow.com/a/17343790/905036
function relativeLuminance(col) {
//Remove any leading #
var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
var components = {};
col = col.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
//Convert hex to 0-1 scale
components = {
r: parseInt(col.substr(0, 2), 16) / 255,
g: parseInt(col.substr(2, 2), 16) / 255,
b: parseInt(col.substr(4, 2), 16) / 255
};
//Correct for sRGB
for (var i in components) {
var v = components[i];
if (v <= 0.03928) {
components[i] = v / 12.92;
}
else {
components[i] = Math.pow(((v + 0.055) / 1.055), 2.4);
}
}
//Calculate relative luminance using ITU-R BT. 709 coefficients
return (components.r * 0.2126) + (components.g * 0.7152) + (components.b * 0.0722);
}
function contrastRatio(c1, c2) {
var y1 = relativeLuminance(c1);
var y2 = relativeLuminance(c2);
//Arrange so y1 is lightest
if (y1 < y2) {
y3 = y1;
y1 = y2;
y2 = y3;
}
return (y1 + 0.05) / (y2 + 0.05);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment