Javascript - 生成随机深色

Sex*_*yMF 8 javascript random colors

我有这种方法为我生成随机颜色的字体:

function getRandomRolor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++) {
         color += letters[Math.round(Math.random() * 15)];
     }
     return color;
}  
Run Code Online (Sandbox Code Playgroud)

问题是字体总是在白色背景上,我想生成深色.
可能吗?
谢谢

P5C*_*der 10

0-5您的颜色的第一个数字中取任意随机数字,然后使用上面的代码选择五个数字中的其余数字.

JS小提琴:http://jsfiddle.net/xP5v8/

var color,
       letters = '0123456789ABCDEF'.split('')
function AddDigitToColor(limit)
{
    color += letters[Math.round(Math.random() * limit )]
}
function GetRandomColor() {
    color = '#'
    AddDigitToColor(5)
    for (var i = 0; i < 5; i++) {
        AddDigitToColor(15)
    }
    return color
}
Run Code Online (Sandbox Code Playgroud)

  • 这不是让它变红了吗? (4认同)

Tom*_*ats 5

您可以使用自定义函数,该函数采用十六进制并按百分比将其变暗lum。您可以修改它以返回您想要返回的任何内容

function ColorLuminance(hex, lum) {
  // validate hex string
  hex = String(hex).replace(/[^0-9a-f]/gi, '');
  if (hex.length < 6) {
    hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
  }
  lum = lum || 0;

  // convert to decimal and change luminosity
  var rgb = "#", c, i;
  for (i = 0; i < 3; i++) {
    c = parseInt(hex.substr(i*2,2), 16);
    c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
    rgb += ("00"+c).substr(c.length);
  }

  return rgb;
}
Run Code Online (Sandbox Code Playgroud)

您也可以只使用hsl(休、饱和度、亮度或亮度)。hsl链接实际上就是经过上面的代码。


Zah*_*med 5

如你所知,RGB at 0,0,0是最暗的黑色,直到(255,255,255)变亮,所以你可以阻止它超过100,只得到深色或说十六进制:

这是jsFiddle

function getRandomRolor() {
    var letters = '0123456789'.split('');
    var color = '#';
    for (var i = 0; i < 6; i++) {
        color += letters[Math.round(Math.random() * 10)];
    }
    return color;
}
Run Code Online (Sandbox Code Playgroud)

  • 它也不应该被称为`getRandomRolor()` (5认同)
  • 这有时会在你的一个颜色数字中给你"未定义",因为例如Math.round(9.6)会舍入到'10'并且该索引超出`letters`数组的范围.请改用Math.floor.另外,我没有看到使用`letters`数组的意义.只需将数字附加到`color`字符串即可. (2认同)