Romain Braun
Romain Braun

Reputation: 3684

Random Hex generator (only grey colors)

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.

Upvotes: 4

Views: 4496

Answers (2)

Zarc Rowden
Zarc Rowden

Reputation: 85

If you want to use RGB, rgb grays can be created by supplying the same number in all three arguments i.e. rgb(255,255,255) (the number must be between 0 and 255).

        function getRandomInt(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min)) + min; 
        }


        var randomNumberString = String(getRandomInt(0,255));
        var color = "rgb(" + randomNumberString + "," + randomNumberString + "," + randomNumberString + ")";

Upvotes: 1

Brian S
Brian S

Reputation: 5056

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

Upvotes: 13

Related Questions