Created
October 2, 2012 04:33
-
-
Save aramk/3816183 to your computer and use it in GitHub Desktop.
JavaScript Hexidecimal Colours
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
/** | |
* Converts a hex color string to an array of 3 ints | |
*/ | |
function hex2RGB(h) { | |
h = h.replace('#', ''); | |
h = h.length == 3 ? shortHexToLong(h) : h; | |
if (h) { | |
var m = h.match(/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/); | |
if (m) { | |
var rgb = []; | |
for (var i = 1; i < m.length; i++) { | |
rgb.push(hex2Dec(m[i])); | |
} | |
return rgb; | |
} else { | |
return null; | |
} | |
} else { | |
return null; | |
} | |
} | |
/** | |
* Converts a shorthand hex to long. E.g. 'f00' = 'ff0000' | |
*/ | |
function shortHexToLong(h) { | |
if (h.length == 3) { | |
j = ''; | |
for (var i in h) { | |
j += h[i] + h[i]; | |
} | |
return j; | |
} else { | |
return null; | |
} | |
} | |
/** | |
* Converts a decimal int to a hex string | |
*/ | |
function dec2Hex(d) { | |
return d.toString(16); | |
} | |
/** | |
* Converts a hex string to a decimal int | |
*/ | |
function hex2Dec(h) { | |
return parseInt(h,16); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment