Randomized RGB colors using JS

58 views Asked by At

I am trying to generate 2 random colors for chart reports by calling this function twice:

function randomNumberGenerator() {
        let color_x = Math.floor(Math.random() * 256);
        let color_y = Math.floor(Math.random() * 256);
        let color_z = Math.floor(Math.random() * 256);
        return `rgba(${color_x}, ${color_y}, ${color_z}, 0.6)`;
}

Everything works fine but the problem is:

Sometimes this function generate 2 random numbers close in the color itself for example grey and light grey.

What I am trying to do is getting two random colors totally not close to each other for example: blue and red or dark-orange and green.

2

There are 2 answers

0
Brad On BEST ANSWER

Some possible alternative solutions:

  • Use something like a triadic color scheme and let the random value choose the initial color, with the rest being algorithmic. This is especially easy if you're using HSL... randomly select the hue, then the secondary color is some number of degrees from that initial hue.
  • Use HSL instead of RGB for your random, with a fixed saturation and lightness and only randomize the hue.
  • Write a function that determines how close the colors are together, (in terms of HSL, probably not RGB) and re-generate if they're too close.
0
DCR On

There are lots of ways you can do this. Here's one:

call your function once. determine x,y,and z as you currently do. For the second color square x,y and z and then mod each with 256 for your second color