How to create random hex code that has a lighter color in javascript?

I use a random color for the background, but since the text is black when really dark colors are generated, the text cannot be seen. How to eliminate these dark colors when generating hexadecimal code?

I could only figure out how to do this:

Math.floor(Math.random()*16777215).toString(16)

But this does not exclude dark colors. Can someone please help me?

Thank you in advance!

+4
source share
3 answers

What I would do is generate a number from 00 to FF for each (RGB) (i.e., 000000 to FFFFFF ). I would also like to make sure that the value of G is approximately above 33.

+4
source

The higher the values, the brighter the color will be, you can try to add a random value to a large number ( 200 in this case):

 var randValue = Math.floor(Math.random()*56)+200; //200 to 255 

Note: the maximum value of HEX is FF , which is equal to the decimal value of 255

You can then convert these RBG values โ€‹โ€‹to HEX using .toString(16) , but as far as I know, you can set colors using RBG values.

Here is the jsFiddle Demo

+6
source

random RGB without numbers 1 and 2, so you get nice colors, with less code:

 var randomColor = (function lol(m, s, c) { return s[m.floor(m.random() * s.length)] + (c && lol(m, s, c - 1)); })(Math, '3456789ABCDEF', 4); 

JSFiddle Demo

+3
source

All Articles