Skip to content

Instantly share code, notes, and snippets.

@joeyred
Last active October 9, 2021 04:49
Show Gist options
  • Select an option

  • Save joeyred/d90737343b539ab12ac19f4611820e45 to your computer and use it in GitHub Desktop.

Select an option

Save joeyred/d90737343b539ab12ac19f4611820e45 to your computer and use it in GitHub Desktop.

Revisions

  1. joeyred revised this gist Oct 9, 2021. 1 changed file with 33 additions and 1 deletion.
    34 changes: 33 additions & 1 deletion RGBAToHexA.ts
    Original file line number Diff line number Diff line change
    @@ -1 +1,33 @@
    ‎‎
    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}`
    }
  2. joeyred created this gist Oct 9, 2021.
    1 change: 1 addition & 0 deletions RGBAToHexA.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    ‎‎