I want to change 6 squares colors all in once and each with a different color.
function randomNum() {
return Math.floor(Math.random() * 256);
}
function randomRGB() {
var red = randomNum();
var green = randomNum();
var blue = randomNum();
return [red,green,blue];
}
I have this JavaScript code that generates random RGB colors values. How can I make it so that each square gets a random color each time I refresh? I can do it with 6 lines of code, but I’m trying to learn easier ways to code. If anyone can do it in a simpler code, I would be grateful!
3
Answers
Your current code is reasonably short and quite readable. Consider sticking with it.
Alternatives include
Array.from
withrandomNum
as a mapper function to construct an array with 3 random valuesIf you want to do this 6 times, then you might use another
Array.from
.You can simply grid a six digit hexadecimal number and then use them for your color.
Like the following number for example:
#ffffff
(which is white)A simple approach: use the hsl() color function and generate a random Hue color (from 0 to 360)
The nice thing about it is that you only change the Hue (color), but the saturation and lightness remain the same for all your elements.
Example with desaturated, darker colors:
Eventually you can generate also a random value in range for the Lightness and Saturation (0 to 100 %)