Skip to content

Instantly share code, notes, and snippets.

@joeyred
Last active October 9, 2021 04:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joeyred/d90737343b539ab12ac19f4611820e45 to your computer and use it in GitHub Desktop.
Save joeyred/d90737343b539ab12ac19f4611820e45 to your computer and use it in GitHub Desktop.
Convert RGB(A) to Hex(A)
interface RGBA {
red: number
green: number
blue: number
alpha?: number
}
const RGBAToHexA = ({ red, green, blue, alpha }: RGBA): string => {
// We are using a system where 16 representations of value
// exist (0-9, a-f) This will give us the hex representation
// of 0-255, which is 256 total values.
let redHex = red.toString(16)
let greenHex = green.toString(16)
let blueHex = blue.toString(16)
let alphaHex
// Handle instances where the hex value assigned
// only has a single digit.
if (redHex.length === 1) redHex = `0${redHex}`
if (greenHex.length === 1) greenHex = `0${greenHex}`
if (blueHex.length === 1) blueHex = `0${blueHex}`
// If alpha is passed, then handle it and return a 9 digit hex
if (alpha) {
alphaHex = Math.round(alpha * 255).toString(16)
if (alphaHex.length === 1) alphaHex = `0${alphaHex}`
return `#${redHex}${greenHex}${blueHex}${alphaHex}`
}
// Else return a 6 digit hex
return `#${redHex}${greenHex}${blueHex}`
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment