4

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!

areke
  • 1,093
  • 1
  • 14
  • 23
  • Using alpha could be one way. – closure Dec 12 '12 at 05:38
  • 1
    Something that might help you - http://stackoverflow.com/questions/6187738/ruby-generate-a-random-hex-color-only-light-colors – painotpi Dec 12 '12 at 05:39
  • This one too, it's almost what you want (remove 0 to 8, for example) http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript – Diego Basch Dec 12 '12 at 05:40
  • You could use a bitwise OR to ensure some of the high bits are always set. Something like `c = (Math.floor(Math.random()*0xffffff)|0x0f0f0f).toString(16);` – david Dec 12 '12 at 05:48

3 Answers3

9

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

ajax333221
  • 11,436
  • 16
  • 61
  • 95
4

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.

KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • 1
    Thanks! I just used this code instead: `(Math.floor((Math.random()*222)+33).toString(16))+(Math.floor((Math.random()*222)+33).toString(16))+(Math.floor((Math.random()*222)+33).toString(16))` Really dark colors are no longer generated... Thank you! – areke Dec 12 '12 at 05:57
  • @areke I think your code produces from decimal 33 to 254. And decimal 33 is 21 HEX. (meaning that you can get `#212121` which is pretty dark, it is darker than the text-color of comments here in SO) – ajax333221 Dec 12 '12 at 06:10
  • 33 hex is 51 decimal. So just change it to 51 if you are using decimal values. – KingKongFrog Dec 12 '12 at 06:15
  • @KingKongFrog 33 hex is too low, even 99 hex (or 153 decimal) is very dark, just look [how dark they are](http://jsfiddle.net/tWyq6/3/) – ajax333221 Dec 12 '12 at 06:51
3

random RGB without the numbers 1 & 2, so you get nice colors, done 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