Best way to generate a random color in javascript?

2019-01-21 04:13发布

What is the best way to generate a random color in JavaScript Without using any frameworks...

Here are a couple of solutions I came up with:

function get_random_color() 
{
    var color = "";
    for(var i = 0; i < 3; i++) {
        var sub = Math.floor(Math.random() * 256).toString(16);
        color += (sub.length == 1 ? "0" + sub : sub);
    }
    return "#" + color;
}

function get_rand_color()
{
    var color = Math.floor(Math.random() * Math.pow(256, 3)).toString(16);
    while(color.length < 6) {
        color = "0" + color;
    }
    return "#" + color;
}

Are there better ways to do it?

10条回答
ら.Afraid
2楼-- · 2019-01-21 04:30

A shorter way:

'#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)
查看更多
Root(大扎)
3楼-- · 2019-01-21 04:36

I have created a slightly more complicated solution but one which lets you control the saturation of the colors and the brightness. You can check out the code for SwitchColors.js here https://github.com/akulmehta/SwitchColors.js

查看更多
姐就是有狂的资本
4楼-- · 2019-01-21 04:39

This answer is the best method.

You should provide known colors to choose from instead of relying on purely numeric methods. You can use sites like ColorBrewer to choose color palettes that work well depending on the problem (qualitative dataset, quantitative, or whatever..)

['red','orange','yellow','green','blue','purple'][Math.random()*6|0]

var colors = {
  rainbow: ['red', 'orange', 'yellow', 'green', 'blue', 'purple'],
  qual: ['#8dd3c7', '#ffffb3', '#bebada', '#fb8072', '#80b1d3', '#fdb462', '#b3de69', '#fccde5', '#d9d9d9', '#bc80bd', '#ccebc5', '#ffed6f'],
  quant: ['#fff7ec', '#fee8c8', '#fdd49e', '#fdbb84', '#fc8d59', '#ef6548', '#d7301f', '#b30000', '#7f0000'],
  div: ['#67001f','#b2182b','#d6604d','#f4a582','#fddbc7','#f7f7f7','#d1e5f0','#92c5de','#4393c3','#2166ac','#053061']
};
randc = function(array) {
  return array[Math.random() * array.length | 0]
}
genc = function() {
  var frag = [];
  var arr = colors[$("select").val()];
  for (var i = 0; i < 1024; i++) {
    frag.push("<div style='background-color:" + randc(arr) + ";'></div>");
  }
  $("#demo").html(frag.join(''));
}
genc();
$("select").on("change", genc);
#demo {
  margin-top: 10px;
  font-size: 0;
}
#demo div {
  display: inline-block;
  width: 24px;
  height: 24px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value='qual'>Qualitative (categorical)</option>
  <option value='quant'>Quantitative (sequential)</option>
  <option value='div'>Divergent (republicans versus democrats)</option>
  <option value='rainbow'>Rainbow (my little pony)</option>
</select>
<div id='demo'></div>

查看更多
Bombasti
5楼-- · 2019-01-21 04:40

More succinct:

function get_random_color2() 
{
    var r = function () { return Math.floor(Math.random()*256) };
    return "rgb(" + r() + "," + r() + "," + r() + ")";
}
查看更多
劳资没心,怎么记你
6楼-- · 2019-01-21 04:42

As George said the best way is to use HSL, so you can generate a bunch of random human-distinguishable colours. The similar idea is implemented in Adams Cole answer to the similar question, but his code have random color generator and hsl->hex rgb translator bundled together which makes it hard to understand and modify.

If you use one of the javascript color manipulation libraries (like jquery-color) color generation become trivial:

function rainbow() {
  // 30 random hues with step of 12 degrees
  var hue = Math.floor(Math.random() * 30) * 12;

  return $.Color({
    hue: hue,
    saturation: 0.9,
    lightness: 0.6,
    alpha: 1
  }).toHexString();
};
查看更多
做自己的国王
7楼-- · 2019-01-21 04:43

I did it like this, with the help of other answers:

'#' + parseInt(Math.random() * 0xffffff).toString(16)
查看更多
登录 后发表回答