Best way to generate a random color in javascript?

2019-01-21 04:10发布

问题:

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?

回答1:

A shorter way:

'#'+(0x1000000+(Math.random())*0xffffff).toString(16).substr(1,6)


回答2:

I like your second option, although it can be made a little bit simpler:

// Math.pow is slow, use constant instead.
var color = Math.floor(Math.random() * 16777216).toString(16);
// Avoid loops.
return '#000000'.slice(0, -color.length) + color;


回答3:

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();
};


回答4:

Here's a way to generate a random color and provide the minimum brightness:

function randomColor(brightness){
  function randomChannel(brightness){
    var r = 255-brightness;
    var n = 0|((Math.random() * r) + brightness);
    var s = n.toString(16);
    return (s.length==1) ? '0'+s : s;
  }
  return '#' + randomChannel(brightness) + randomChannel(brightness) + randomChannel(brightness);
}

Call randomColor with a value from 0-255, indicitating how bright the color should be. This is helpful for generating pastels, for example randomColor(220)



回答5:

More succinct:

function get_random_color2() 
{
    var r = function () { return Math.floor(Math.random()*256) };
    return "rgb(" + r() + "," + r() + "," + r() + ")";
}


回答6:

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

'#' + parseInt(Math.random() * 0xffffff).toString(16)


回答7:

function randomColor()
{
     color='rgb('+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+','+Math.round(Math.random()*255)+')';

     return color;
}

This returns a random RGB value.



回答8:

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>



回答9:

Most succinct:

function get_random_color()
{
  return '#' + Math.random().toString(16).substring(4);
}

Nicolas Buduroi gave the above best code to get random color at Random Color generator in Javascript



回答10:

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