If you ever tried to create HTML or SVG graphs, it is most likely that you have asked google the question How to generate random colors in javascript? , because I for sure did ???? .
Maybe you have searched it for some other reason. To create some cool UI or something, or maybe to irritate the user with stupid colors ???? .
If you have never searched it or thought about it, well why don’t you go ahead and try it now, it’s free after all.
There are plenty of resources in the internet that would help you get the job done. But here is my little experiment.
Where to start?
I want a function that would take the number of colors to generate, as input and outputs the generated colors.
Something like this –
//generate colors function gen_colors(no_of_colors_to_generate) { //magic //return an array of colors return colors; }
So I decided to start with one color and tweak and shuffle the RGB values to generate random colors.
function color_gen(len) { //array in which generated //colors are stored colors = []; function gen_colors(colrs, len) { //generate the colors } //start with rgb(180, 54, 54) return gen_colors([180, 54, 54], len); }
The full function
function color_gen(len) { //array in which generated //colors are stored colors = []; function gen_colors(colrs, len) { //loop and create all combinations //of the given color for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { for (var k = 0; k < 3; k++) { var color_arr = [colrs[i], colrs[j], colrs[k]]; //exclude if combination already exists //or have the same values ex rgb(180, 180, 180) if ((colors.indexOf(rgbize_arr(color_arr)) == -1) && !(colrs[i] == colrs[j] && colrs[i] == colrs[k])) { colors.push(rgbize_arr(color_arr)); } //if required colors //grater than 25 repeat the //colors generated if (colors.length >= 25) { colors = colors.concat(colors); } //if required no. of colors //are generated return if (colors.length == len) { return colors; } //if generated > required //return only required else if (colors.length > len) { //console.log(colors.slice(0, len)); return colors.slice(0, len); } //if combinations are over //generate a new first color else { if (i == 2 && i == j && i == k) { var max_colr = Math.max.apply(Math, colrs); var min_colr = Math.min.apply(Math, colrs); var colr1 = Math.floor((max_colr + min_colr) / 4); var colr2 = Math.floor((max_colr + min_colr) / 2); var colr3 = Math.floor((max_colr + min_colr) / 3); return gen_colors([colr1, colr2, colr3], len); } } } } } } //convert array into rgb string function rgbize_arr(colr_arr) { return 'rgb(' + colr_arr.join() + ')'; } return gen_colors([180, 54, 54], len); }
Usage
var new_colors = color_gen(25);
Gotta better technique (highly likely), comment below ???? .
See the color generator in action-
See the Pen Javascript random color generation by hrishikesh mk (@avastava) on CodePen.0