在javascript中按数字随机化颜色

时间:2017-01-27 11:39:28

标签: javascript

我想在javascript中按照给定的id(它可以是从0开始的任何数字)随机化颜色。 例如:

//number is the id I want to give the function
    function getRandomColor(number) {
    var letters = '0123456789ABCDEF';
    var color = '#';
    var generatedNumber = Math.floor(Math.random() * 16);
    var otherNumber = //something to unite generatedNumber and number(the given id) in a valid number
        for (var i = 0; i < 6; i++ ) {
            color += letters[otherNumber];
        }
        return color;
    }

我怎么能这样做?

3 个答案:

答案 0 :(得分:4)

您需要移动for循环内的随机部分。

&#13;
&#13;
function getRandomColor(number) {
    var letters = '0123456789ABCDEF',
        color = '#',
        generatedNumber,
        i;
  for (i = 0; i < 6; i++) {
      generatedNumber = Math.floor(Math.random() * 16);
      color += letters[generatedNumber];
  }
  return color;
}

console.log(getRandomColor());
&#13;
&#13;
&#13;

您可以省略带有数字和字母的字符串,并使用带有基数16的toString

为了保持相同id的相同颜色,您可以使用一个对象来保持颜色。

&#13;
&#13;
function getRandomColor() {
    var color = '#',
        i;
    for (i = 0; i < 6; i++) {
        color += Math.floor(Math.random() * 16).toString(16);
    }
    return color;
}

var getColor = function() {
        var colors = {};
        return function (id) {
            return colors[id] = colors[id] || getRandomColor();
        };
    }();


console.log(getColor('foo'));
console.log(getColor('bar'));
console.log(getColor('baz'));
console.log(getColor('foo'));
console.log(getColor('baz'));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

根据我上面的评论,操作HSL colorspace中的颜色可能会更好,这样您就可以获得大胆的颜色。诀窍是在随机化色调和饱和度的同时保持恒定的亮度。

对于色调和饱和度的任何组合,100%亮度始终为白色,0%亮度始终为黑色。可以看到最强烈的颜色印象,亮度值恰好在中间,即50%。

您可以按照以下方式执行此操作:

&#13;
&#13;
var h = Math.floor(Math.random() * 360); //hue is measured in degrees from 0-359
var s = Math.floor(Math.random() * 256); //saturation is a value from 0-255


$("#theElement").css("background-color","hsla(" + h + ", " + s + "%, 50%, 1)");
&#13;
#theElement{
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=theElement></div>
&#13;
&#13;
&#13;

所以,假设您要生成16种颜色的调色板:

var colors = [];
for(var i = 0; i < 16; ++i)
{
    var h = Math.floor(Math.random() * 360); //hue is measured in degrees from 0-359
    var s = Math.floor(Math.random() * 256); //saturation is a value from 0-255
    colors.push("hsla(" + h + ", " + s + "%, 50%, 1)");
}
var paletteIndex = 3; //for example
$("#theElement").css("background-color", colors[paletteIndex]);

答案 2 :(得分:0)

var possibilities = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
var newColor = '';
var x = 1;
var z = ''
do { 
z = Math.floor((Math.random() * 16) + 1);
    if (possibilities[z] !== undefined){
      newColor = newColor + possibilities[z]; 
      x++;
    }
}
while (x<7);
console.log("#"+newColor)