Skip to content

Instantly share code, notes, and snippets.

@prajwal-stha
Forked from polotek/hex2rgb.js
Created October 8, 2017 11:08
Show Gist options
  • Save prajwal-stha/f0cb4452a314279e0a03be93de1b2dfa to your computer and use it in GitHub Desktop.
Save prajwal-stha/f0cb4452a314279e0a03be93de1b2dfa to your computer and use it in GitHub Desktop.
Convert hex colors to rgba
/**
* 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