How to generate a random RGBA color and opacity in TypeScript

2 Answers

0 votes
/**
 * Generate a random RGBA color in TypeScript.
 *
 * Notes:
 * - Uses Math.random() for uniform random values.
 * - Produces integer RGB values in [0, 255].
 * - Produces opacity (alpha) in [0, 1] with full floating‑point precision.
 * - Returns a formatted CSS RGBA string: "rgba(r, g, b, a)".
 */

/** A strongly typed structure representing an RGBA color. */
type RGBA = {
    r: number;   // red   component (0–255)
    g: number;   // green component (0–255)
    b: number;   // blue  component (0–255)
    a: number;   // alpha component (0–1)
};

/** Generate a random integer in the range [0, 255]. */
function randomChannel(): number {
    return Math.floor(Math.random() * 256);
}

/** Generate a random opacity value in the range [0, 1]. */
function randomOpacity(): number {
    return Math.random();
}

/** Create a random RGBA color object. */
function generateRandomRGBA(): RGBA {
    return {
        r: randomChannel(),
        g: randomChannel(),
        b: randomChannel(),
        a: randomOpacity()
    };
}

/** Convert an RGBA object into a CSS rgba(...) string. */
function rgbaToCss(color: RGBA): string {
    const { r, g, b, a } = color;
    
    return `rgba(${r}, ${g}, ${b}, ${a.toFixed(3)})`; 
    // toFixed(3) keeps opacity readable while still precise
}

/** Example usage */
const color: RGBA = generateRandomRGBA();
const cssString: string = rgbaToCss(color);

console.log("Generated RGBA color object:", color);
console.log("CSS RGBA string:", cssString);


/*
run:

Generated RGBA color object: { r: 36, g: 157, b: 91, a: 0.4803201838549229 }
CSS RGBA string: rgba(36, 157, 91, 0.480)

*/

 



answered Aug 25 by avibootz
0 votes
/**
 * Generate a random RGBA color string.
 * Produces full‑range RGB values and a floating‑point opacity.
 */

function randomRGBA(): string {
    const randomChannel: () => number = () =>
        Math.floor(Math.random() * 256);

    const randomOpacity: () => number = () =>
        Math.random(); // full precision

    const r: number = randomChannel();
    const g: number = randomChannel();
    const b: number = randomChannel();
    const a: number = randomOpacity();

    return `rgba(${r}, ${g}, ${b}, ${a.toFixed(2)})`;
}

const color: string = randomRGBA();
console.log(color);


/*
run:

rgba(21, 122, 151, 0.84)

*/

 



answered Aug 25 by avibootz
...