Jony Talassazan - 6 months ago 9
Javascript Question

# Limiting colors when using getRandomColor

I have setup a basic getRandomColor function in javascript but I am having trouble figuring out how to limit the color spectrum that it uses. I want it to be more White & Grey colors. Is this possible?

My code is as follows:

``````function getRandomColor() {
var letters = "0123456789ABCDEF".split("");
var color = "#";
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
``````

Go to an online color picker like this one, and look through a bunch of grey/white/black colors. On the webpage I linked to, you can do this by clicking to the verrrry left of the color box.

Look and see if you can find a pattern in the ratio between red/blue/green in the colors you want. Let me know if you find the pattern.

## Edit

Alright, I'll let the cat out of the bag like the other answer has already done. When we have a 6-digit hex code, we have 2 digits for red, 2 digits for blue, and 2 digits for green.

``````        # 80  80  80
^   ^    ^
red amount  |    |-----green amount
|---------------- blue amount
``````

Numbers with a high red amount are very red, (like `#990000` or `#ff0000`) numbers with a high blue amount are very blue (`#00ff00`), etc...

If the amount of red, green, and blue are all the same, then the color will look grey. So, all of the following colors will be grey-ish

``````#757575
#343434
#a3a3a3
``````

Because I copied the same 2 numbers over and over. In the first one, the red amount is the same as the blue amount is the same as the green amount, which is 75.

Now how do you get this into your code? Generate 2 random letters to get the first color, and then add that to the end of your string 2 more times.

Source (Stackoverflow)