Skip to content

Instantly share code, notes, and snippets.

@bel0v
Last active July 25, 2023 16:04
Show Gist options
  • Save bel0v/ccd07374db40a9e2692c63c71b4a7335 to your computer and use it in GitHub Desktop.
Save bel0v/ccd07374db40a9e2692c63c71b4a7335 to your computer and use it in GitHub Desktop.
"flatten" rgba with transparency by blending it with white
function hexify(color) {
const values = color
.replace(/rgba?\(/, '')
.replace(/\)/, '')
.replace(/[\s+]/g, '')
.split(',')
const a = parseFloat(values[3] || 1)
const r = Math.round(a * parseInt(values[0]) + (1 - a) * 255)
const g = Math.round(a * parseInt(values[1]) + (1 - a) * 255)
const b = Math.round(a * parseInt(values[2]) + (1 - a) * 255)
const hex =
("0" + r.toString(16)).slice(-2) +
("0" + g.toString(16)).slice(-2) +
("0" + b.toString(16)).slice(-2)
return { hex: `#${hex}`, rgba: `rgba(${r}, ${g}, ${b}, 1)`}
}
var myHex = hexify('rgba(194, 226, 250, 0.8)'); // {hex: '#cee7fb', rgba: 'rgba(206, 231, 251, 1)'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment