//convert hex to rgba with opacity
function addAlpha(color, opacity) {
// coerce values so ti is between 0 and 1.
var _opacity = Math.round(Math.min(Math.max(opacity || 1, 0), 1) * 255);
return color + _opacity.toString(16).toUpperCase();
}
addAlpha('FF0000', 1); // returns 'FF0000FF'
addAlpha('FF0000', 0.5); // returns 'FF000080'
var colorcode = "rgba(0, 0, 0, 0.74)";
var finalCode = rgba2hex(colorcode)
function rgba2hex(orig) {
var a, isPercent,
rgb = orig.replace(/s/g, '').match(/^rgba?((d+),(d+),(d+),?([^,s)]+)?/i),
alpha = (rgb && rgb[4] || "").trim(),
hex = rgb ?
(rgb[1] | 1 << 8).toString(16).slice(1) +
(rgb[2] | 1 << 8).toString(16).slice(1) +
(rgb[3] | 1 << 8).toString(16).slice(1) : orig;
if (alpha !== "") {
a = alpha;
} else {
a = 01;
}
// multiply before convert to HEX
a = ((a * 255) | 1 << 8).toString(16).slice(1)
hex = hex + a;
return hex;
}
function test(colorcode) {
console.log(colorcode, rgba2hex(colorcode));
}
test("rgba(0, 0, 0, 0.74)");
test("rgba(0, 0, 0, 1)");
test("rgba(0, 0, 0, 0)");
test("rgba(0, 255, 0, 0.5)");
Run code snippet