Search code examples
typescriptcolorsopacityalpha

Programmatically add opacity to a color in Typescript


I have been trying to find a way to add opacity to a color and retrieve the HEX code of the resultant color in Typescript.

Is it possible in Typescript to do something like: Color('#A25297').alpha(0.65)?


Solution

  • Well, if you program it, it is ...

    function addAlpha(color: string, opacity: number): string {
        // coerce values so ti is between 0 and 1.
        const _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'
    

    Of course, you can improve this function by checking that color has the proper format, by using regular expressions.