Question

I'd like to generate a random color, based on an original color and a normal distribution, so I can create a random texture telling the script "Okay, this is the general color you should be using, but if you differ greatly every now and then, that's fine".

I'm writing in JavaScript, using the Box-Muller transform. But if I use the normal distribution independently on every R, G and B value, I get undesired spikes. If my base color is a light grey, for example, I get pixels that are very red, very green or very blue. This is my script so far ("0, 255" being min and max):

function randomHex(hex, deviation){
    R = HexToR(hex);
    G = HexToG(hex);
    B = HexToB(hex);
    R = randomNormal(R, deviation, 0, 255);
    G = randomNormal(G, deviation, 0, 255);
    B = randomNormal(B, deviation, 0, 255);
    return RGBtoHex(R,G,B);
}

I think what I'm looking for is to somehow define a point in the 3D space of RGB color and then select a (uniformly distributed) random point on a sphere who's center is the defined point and who's radius is randomly generated with normal distribution.

That's the theory, anyway. I just don't have a clue how to make that work in JavaScript.

I'd be thankful for any pointers!

Was it helpful?

Solution

I'd try using HSV (or perhaps HSL) instead of RGB. You'll need a function to convert back to RGB (see here for an example). In this case, H is the hue, and your value is some position on a circle of colors. S and V control saturation and value/brightness respectively. I think this will give you more control to get the distributions you're after. More info on wikipedia here too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top