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条回答
孤傲高冷的网名
2楼-- · 2019-01-21 04:44

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;
查看更多
Emotional °昔
3楼-- · 2019-01-21 04:47

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

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-21 04:52

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楼-- · 2019-01-21 04:56
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.

查看更多
登录 后发表回答