Created
April 17, 2012 21:54
-
-
Save quickredfox/2409334 to your computer and use it in GitHub Desktop.
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
HEXCHARS = '0123456789ABCDEF'.split('') | |
rgb2hex = (r,g,b)-> "##{byte2hex(r)}#{byte2hex(g)}#{byte2hex(b)}" | |
byte2hex = (n)-> String(HEXCHARS.substr((n >> 4) & 0x0F,1)) + HEXCHARS.substr(n & 0x0F,1) | |
hex2rgb = ( color )-> | |
triplet = color.toLowerCase().replace /#/ , '' | |
rgb = [] | |
if triplet.length is 6 | |
rgb[0] = parseInt(triplet.substr(0,2), 16) | |
rgb[1] = parseInt(triplet.substr(2,2), 16) | |
rgb[2] = parseInt(triplet.substr(4,2), 16) | |
return rgb | |
else if triplet.length is 3 | |
rgb[0] = parseInt((triplet.substr(0,1) + triplet.substr(0,1)), 16) | |
rgb[1] = parseInt((triplet.substr(1,1) + triplet.substr(1,1)), 16) | |
rgb[2] = parseInt((triplet.substr(2,2) + triplet.substr(2,2)), 16) | |
return rgb | |
else throw triplet + ' is not a valid color triplet.' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment