简体   繁体   中英

Javascript random hex generator returns complementary colours

I have the following code:

function get_random_color() {
    return '#' + Math.floor((Math.random() * 0xF00000) + 0x0FFFFF).toString(16);
}

for (var i=0; i<5; i++)
  {
      $(".colors").append("<div style='background:"+get_random_color()+"'></div>");
  }

HTML

<div class="colors"></div>

CSS

.colors > div{width:30px; height:30px;}

However the "random" generation seems to create an assortment of almost complementary colours:

在此处输入图片说明在此处输入图片说明在此处输入图片说明在此处输入图片说明在此处输入图片说明

Why isn't my code fully random and colours always seem to match?

Example:

http://jsfiddle.net/SaRT6/

I wouldn't say that they matched exactly, but I get your drift!

I think this boils down to maths and probability, not that I'm an expert in that area, but if you think about it you have three ranges, and to end up with black for example you need all three of those random numbers to match at the extreme end of the range. That is less likely to happen than three non-matching numbers as you can imagine. You're much more likely to get numbers that sit within that range somewhere than numbers that that are at the very extremes. If you now look at a few common colours many of them will rely on one of those numbers being zero or near zero, or possibly the other end at 255. To get black you've got 1 in 16.5 million chance of getting it. Same for any of the greys.

So the solution? If you don't need too many colours, simply make an array of different 'nice' colours and pick them from that using a random index.

Here is my suggestion using CSS3's HSL model. This uses a fixed Saturation and Lightness and varies Hue a bit -- you could also vary S and L the same way.

function get_random_color(H,S,L) {
  return 'hsl(' + ((H+Math.floor(Math.random() * 60))%360) + ','+S+'%,'+L+'%)' ;
}

randomS = Math.round(Math.random()*25)+75; // not too gray!
randomL = Math.round(Math.random()*20)+50-10; // not too light!
randomH = Math.floor(Math.random()*360);
for (var i=0; i<5; i++)
{
  $(".colors").append("<div style='background:"+get_random_color(randomH,randomS,randomL)+";'></div>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM