Created
June 9, 2014 08:57
-
-
Save mstssk/afda4ce9e5c335fd79cd to your computer and use it in GitHub Desktop.
rgba2hex.js
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
/** | |
* Converts RGB or RGBA format to Hex format. | |
* e.g. "rgb(28, 166, 171)" -> "#1ca6ab" | |
* | |
* @param rgba A color of RGB or RGBA format. | |
* @return A color of Hex format; | |
*/ | |
function rgba2hex(rgba) { | |
var regex = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?\)/ | |
parsed = regex.exec(rgba), red, green, blue, alpha, elems; | |
if (!parsed) { | |
throw "Invalid format: " + rgba; | |
} | |
red = parsed[1]; | |
green = parsed[2]; | |
blue = parsed[3]; | |
alpha = parsed[4]; | |
elems = [hex(red), hex(green), hex(blue)]; | |
if (alpha) { | |
elems.push(hex(alpha)); | |
} | |
return "#" + elems.join(""); | |
function hex(number) { | |
if (number > 255) { | |
throw "'" + number + "'' is greater than 255(0xff);"; | |
} | |
var str = Number(number).toString(16); | |
return ("0" + str).slice(-2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment