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)
您可以使用自定义函数,该函数采用十六进制并按百分比将其变暗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链接实际上就是经过上面的代码。
如你所知,RGB at 0,0,0是最暗的黑色,直到(255,255,255)变亮,所以你可以阻止它超过100,只得到深色或说十六进制:
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)
| 归档时间: |
|
| 查看次数: |
10128 次 |
| 最近记录: |