Why not make your own color generator 🌈?
Method 1 - Long method
// Generate random color in hex format
const randomColor = () => {
const letters = "0123456789ABCDEF";
let color = "#";
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
Method 2 - Short and Best Method
const randomColor = Math.floor(Math.random()*16777215).toString(16);
console.log("#" + randomColor)
Thank you for reading, have a nice day!
- Follow me on Twitter - @codewithsnowbit
- Subscribe me on YouTube - Code With SnowBit
Top comments (1)
Interesting that so many random color solutions suffer from the same off-by-one error (I left the same comment on the post Our favorite javascript one-liners):
16777215 == 0xffffff
, which is the max "value" for a hex color; however,Math.floor(Math.random() * n)
gives integers in the range0..(n - 1)
, not0..n
. For example,Math.floor(Math.random() * 2)
will always give0
or1
, never2
.If you want to have the possibility of ever generating pure white (
0xffffff
), you instead need to use a multiplier of0xffffff + 1
: