Skip to content

Instantly share code, notes, and snippets.

@jastkand
Created December 11, 2018 14:47
Show Gist options
  • Save jastkand/86cc10cfa0461e8e2075e8cab21f4bd9 to your computer and use it in GitHub Desktop.
Save jastkand/86cc10cfa0461e8e2075e8cab21f4bd9 to your computer and use it in GitHub Desktop.
hexToRGBA
// https://stackoverflow.com/questions/15898740/how-to-convert-rgba-to-a-transparency-adjusted-hex
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);
}
let myHex = hexify('rgba(57,156,29,0.05)'); // "#f5faf3"
console.log(myHex);
function hexToRgb(hex) {
let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function hexToRGBA(hex, alpha) {
let color = hexToRgb(hex);
let r = Math.floor((color.r - 255 * (1 - alpha)) / alpha);
let g = Math.floor((color.g - 255 * (1 - alpha)) / alpha);
let b = Math.floor((color.b - 255 * (1 - alpha)) / alpha);
return `rgba(${r}, ${g}, ${b}, ${alpha})`
}
let myRGBA = hexToRGBA('#f5faf3', 0.05); // "rgba(55, 155, 15, 0.05)"
console.log(myRGBA);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment