//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'
function hexify(color) {
var values = color
.replace(/rgba?(/, '')
.replace(/)/, '')
.replace(/[s+]/g, '')
.split(',');
var a = parseFloat(values[3] || 1),
r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255);
return "#" +
("0" + r.toString(16)).slice(-2) +
("0" + g.toString(16)).slice(-2) +
("0" + b.toString(16)).slice(-2);
}
var myHex = hexify('rgba(255,255,255,0.6)'); // "#f5faf3"
console.log(myHex);