问题
I have this method to generate me random colors for font:
function getRandomRolor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
The problem is that the font is always on white background, I want to generate dark colors.
Is it possible?
Thanks
回答1:
You could use a custom function that takes a hex and darkens it by the percent lum
. You can modify it to return whatever you want back
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;
}
You could also just use hsl (Hugh, Saturation, Luminosity or Lightness). The hsl link actually goes through the above code.
回答2:
Take any random digit from 0-5
as the first digit of your color and then choose the rest of the five digits using your above code.
JS Fiddle: 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
}
回答3:
As you know RGB at 0,0,0
is black the darkest and it goes toward getting light until (255,255,255) so you can stop it to go above 100, to get only dark color or say 9 in hex:
Here is 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;
}
来源:https://stackoverflow.com/questions/20114469/javascript-generate-random-dark-color