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.
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
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 than1e7
(decimal 10,000,000).Math.random
is inclusive of the lower bound but not the upper bound, soMath.floor(Math.random() * 0x1_00_00_00)
gives a number in the range0x00_00_00..0xff_ff_ff
(pure black to pure white).1e7 - 1
(the maximum value with1e7
as upper bound), on the other hand, converts to0x98_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.
Good point, it's not a failsafe method indeed thanks for this addition Lionel!
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
instead.
Good point, forgot about that. A simpler fix would probably be
hexStr.padStart(6, '0')
.