I found on stackoverflow this color generator :
Math.random()*0xFFFFFF<<0
It works fine. The only problem is that I'd like to generate random colors, but only of different shades of grey.
I have no idea how I could achieve something like this.
var value = Math.random() * 0xFF | 0;
var grayscale = (value << 16) | (value << 8) | value;
var color = '#' + grayscale.toString(16);
color
will be a random grayscale hex color value, appropriate for using in eg element.style
properties.
Note: there are several ways to coerce the random floating-point number to an integer. Bitwise OR (x | 0
) will usually be the fastest, as far as I know; the floor function (Math.floor(x)
) is approximately the same speed, but only truncates for positive numbers (you'd have to use Math.ceil(x)
for negative numbers). Bitwise operators won't work as expected for numbers that require more than 32 bits to represent, but Math.random() * 0xFF
will always be in the range [0,255)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With