Last active
December 28, 2015 04:19
-
-
Save christophemarois/7441363 to your computer and use it in GitHub Desktop.
shouldTextBeDark v 1.0
Determines whether text color should be dark or not to contrast nicely with the background color, based on the visual contrast algorithm suggested by the W3C (http://www.w3.org/WAI/ER/WD-AERT/#color-contrast).
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
// shouldTextBeDark v 1.0 | |
// (formerly colorContrast) | |
// Determines whether text color should be dark or not to | |
// contrast nicely with the background color. | |
// Based on the visual contrast algorithm suggested by the W3C | |
// (http://www.w3.org/WAI/ER/WD-AERT/#color-contrast) | |
// Call it with a RGB color: | |
// e.g. shouldTextBeDark.rgb(225, 255, 255) => true | |
// Or with a HEX color: | |
// e.g. shouldTextBeDark.hex('#FF0000') => false | |
var shouldTextBeDark = new function() { | |
var _hexToRgb = function(hex) { | |
var channels = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); | |
return channels ? { | |
r: parseInt(channels[1], 16), | |
g: parseInt(channels[2], 16), | |
b: parseInt(channels[3], 16) | |
} : null; | |
}; | |
var _calculate = function(r, g, b) { | |
var contrast = ((r*299)+(g*587)+(b*114)) / 255000; | |
return contrast >= 0.5 ? true : false; | |
}; | |
this.rgb = function(r, g, b) { | |
return _calculate(r, g, b); | |
}; | |
this.hex = function(hex) { | |
var rgb_a = _hexToRgb(hex); | |
return _calculate(rgb_a.r, rgb_a.g, rgb_a.b); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment