-
-
Save prajwal-stha/f0cb4452a314279e0a03be93de1b2dfa to your computer and use it in GitHub Desktop.
Convert hex colors to rgba
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
/** | |
* hex2rgb - function for converting hex colors to rgb(a) | |
* | |
* Shout out to http://hex2rgba.devoth.com/ | |
* | |
* @hex (String) - The hex value. Can be prefixed with "#" or not. Can be | |
* long format (6 chars) or short format (3 chars) | |
* @opacity (number between 0 and 1) - This is an optional float value that | |
* will be used for the opacity | |
* | |
* returns (Object) - an object with r, g, and b properties set as numbers | |
* along with a "css" property representing the css rule as a string | |
*/ | |
function hex2rgb(hex, opacity) { | |
hex = (hex + '').trim(); | |
var rgb = null | |
, match = hex.match(/^#?(([0-9a-zA-Z]{3}){1,3})$/); | |
if(!match) { return null; } | |
rgb = {} | |
hex = match[1]; | |
// check if 6 letters are provided | |
if (hex.length == 6) { | |
rgb.r = parseInt(hex.substring(0, 2), 16); | |
rgb.g = parseInt(hex.substring(2, 4), 16); | |
rgb.b = parseInt(hex.substring(4, 6), 16); | |
} | |
else if (hex.length == 3) { | |
rgb.r = parseInt(hex.substring(0, 1) + hex.substring(0, 1), 16); | |
rgb.g = parseInt(hex.substring(1, 2) + hex.substring(1, 2), 16); | |
rgb.b = parseInt(hex.substring(2, 3) + hex.substring(2, 3), 16); | |
} | |
rgb.css = 'rgb' + (opacity ? 'a' : '') + '('; | |
rgb.css += rgb.r + ',' + rgb.g + ',' + rgb.b; | |
rgb.css += (opacity ? ',' + opacity : '') + ')'; | |
return rgb; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment