Created
December 3, 2014 12:33
-
-
Save veganben/d0815a0cf0ac0e91bdcc to your computer and use it in GitHub Desktop.
Get a contrasting colour. Put a black label on a light background, a white label on a light one. For example.
This file contains hidden or 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
| /** | |
| * @param hex {String} hex colour with or without hash | |
| * @returns {String} black if the original colour was light, white if it was dark. With hash if it had it in the first place. | |
| */ | |
| getContrastMonochrome = function (hex) { | |
| var colour = hex, | |
| sum, | |
| hasHas = false; | |
| hex = hex.charAt(0) === "#" ? hasHash = hex.substring(1) : hex; | |
| sum = (function(h){ | |
| var sum = 0; | |
| for(var i = 0; i < h.length; i+=2){ | |
| sum += parseInt(h.substr(i,2),16); | |
| } | |
| return sum; | |
| })(hex); | |
| // yeah yeah, magic number | |
| // you can replace it with | |
| // (parseInt("ff", 16) * 3) / 2 | |
| // if you really want | |
| colour = sum > 382 ? "000000" : "ffffff"; | |
| if(hasHash) { | |
| colour = "#" + colour; | |
| } | |
| return colour; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment