Created
July 31, 2013 07:06
-
-
Save junaidpv/6119929 to your computer and use it in GitHub Desktop.
Javascript RGB(A) string conversion functions.
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
/** | |
* Parse an rgb or rgba string like 'rgb(67, 216, 89)' or 'rgba(245, 156, 8, 178)' | |
* to array of integers in the order. | |
* Credit: http://stackoverflow.com/questions/10970958/get-a-color-component-from-an-rgb-string-in-javascript | |
**/ | |
function parse_rgb_string(rgb) { | |
rgb = rgb.replace(/[^\d,]/g, '').split(','); | |
return rgb; | |
} | |
/** | |
* Create and hexadecimal string corresponding to given deciman number. | |
**/ | |
function dec_to_hex_string(dec, length) { | |
var hex = dec.toString(16).toUpperCase(); | |
if (hex.length < length) { | |
hex = new Array( length - hex.length + 1 ).join( '0' ) + hex; | |
} | |
return hex; | |
} | |
function rgba_to_hex_string(rgb_string, alpha_percentage) { | |
var rgb_array = parse_rgb_string(rgb_string); | |
if (typeof alpha_percentage !== 'undefined') { | |
var alpha = 255 * alpha_percentage / 100; | |
alpha = Math.floor(alpha); | |
// Apply alpha value replacing existing if there. | |
rgb_array[3] = alpha; | |
} | |
var hex_string = ''; | |
for( var i = 0; i < rgb_array.length; i++) { | |
hex_string += dec_to_hex_string(rgb_array[i], 2); | |
} | |
return '#' + hex_string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment