Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random hex code that of a lighter color in javascript?

Tags:

javascript

hex

I am using a random color for the background, but since the text is black, when really dark colors are generated, the text can't be seen. How do I exclude these dark colors when generating the hexadecimal code?

I could only figure out how to get this:

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

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

Thank you in advance!

like image 349
areke Avatar asked Dec 05 '22 13:12

areke


2 Answers

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

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

Note: the maximum HEX value is FF which equals to decimal 255

Then, you can optionally convert these RBG values to HEX using .toString(16), but as far as I know, you can set colors using RBG values.

Here is a jsFiddle Demo

like image 139
ajax333221 Avatar answered Dec 28 '22 10:12

ajax333221


What I would do is generate a number from 00 to FF for each (RGB) (ie 000000 to FFFFFF). I would also make sure the G value is approximately higher than 33.

like image 28
KingKongFrog Avatar answered Dec 28 '22 11:12

KingKongFrog