DEV Community

Discussion on: Vanilla JavaScript random colours

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

You'll get a more complete distribution throughout the RGB color space using 0x1_00_00_00 (decimal 16,777,216) as a multiplier, rather than 1e7 (decimal 10,000,000). Math.random is inclusive of the lower bound but not the upper bound, so Math.floor(Math.random() * 0x1_00_00_00) gives a number in the range 0x00_00_00..0xff_ff_ff (pure black to pure white). 1e7 - 1 (the maximum value with 1e7 as upper bound), on the other hand, converts to 0x98_96_7f, which is a sort of beige color.

I think that's why the colors you're generating are skewing toward greens and purples, bearing in mind that contiguous 6-digit hex numbers don't always look like similar colors, seeing as they're split into red-green-blue segments.

Collapse
 
dailydevtips1 profile image
Chris Bongers

Good point, it's not a failsafe method indeed thanks for this addition Lionel!

Collapse
 
lexlohr profile image
Alex Lohr • Edited

You'll still have a chance to hit a number low enough not to yield a 3- or 6-digit hex number, which will result in an invalid color (0x0-0xFF, 0x1000-0xfffff). To solve that, you can use

'#' + (0x1000000 + 0x1000000 * Math.random() | 0).toString(16).slice(-6)
Enter fullscreen mode Exit fullscreen mode

instead.

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Good point, forgot about that. A simpler fix would probably be hexStr.padStart(6, '0').