Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Hex generator (only grey colors)

Tags:

javascript

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.

like image 452
Romain Braun Avatar asked Dec 12 '22 06:12

Romain Braun


1 Answers

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).

like image 150
Brian S Avatar answered Dec 25 '22 14:12

Brian S