Random Color Generation in JavaScript
Generate random hex, RGB, and HSL colors in JavaScript — with seeding, palettes, and accessible variants.
Published:
Tags: random color JavaScript, generate random hex color JS, JavaScript random color code
Random Color Generation in JavaScript Random colors require choosing a randomness source ( for aesthetics, for security) and a color space. HSL is superior to RGB because controlling saturation and lightness independently avoids muddy or washed-out colors. Seeded PRNGs enable deterministic colors for avatars. --- What about The Simplest Approach: Random Hex Color? This generates a value from 0 to 16,777,215 (2²⁴ − 1), converts to hex, and pads to ensure exactly 6 characters. Without , colours with leading zeros (like ) would render as . What about Separate RGB Channel Generation? Working with separate channels makes it easier to constrain individual components (e.g. always high blue) or convert to other colour spaces. What about Cryptographic Randomness with crypto.getRandomValues? is a…
Frequently Asked Questions
How do I generate a random hex color in JavaScript?
Generate a random integer from 0 to 16777215 (0xFFFFFF), convert to hex with toString(16), and pad to 6 characters: `'#' + Math.floor(Math.random() * 0xFFFFFF).toString(16).padStart(6, '0')`. For cryptographic randomness, use `crypto.getRandomValues(new Uint8Array(3))` to generate three random bytes for R, G, and B.
How do I generate a random RGB color?
Generate three values in the range 0–255: `const r = Math.floor(Math.random() * 256)` for each channel. Combine as `rgb(${r}, ${g}, ${b})` for a CSS value or return an object `{ r, g, b }` for programmatic use. For typed arrays, `crypto.getRandomValues(new Uint8Array(3))` returns three random bytes directly.
How do I make a random color that is readable?
Avoid very dark or very light random colours by constraining the lightness in HSL. Generate a random hue (0–360), fix saturation at 60–80%, and constrain lightness to 35–65%. This avoids near-white and near-black colours. For guaranteed WCAG contrast, calculate the contrast ratio between the generated colour and your background and reject colours below 4.5:1.
How do I generate accessible random colors?
Generate random colours in HSL with constrained lightness (20–80% for dark backgrounds, 20–60% for light backgrounds). Then verify the WCAG 2.1 contrast ratio using the relative luminance formula. If the ratio is below 4.5:1 (AA) or 7:1 (AAA), adjust the lightness until it passes or regenerate.
How do I seed a random color generator?
JavaScript's Math.random() is not seedable. For repeatable random colours from a seed (e.g. a user ID or entity name), use a seeded PRNG like mulberry32 or sfc32. Pass the seed value and generate RGB/HSL values from the PRNG output. This ensures the same input always produces the same colour — useful for user avatars and chart series colouring.
All articles · theproductguy.in