如果我理解正确的话。试试下面的功能。如果您随机传递任何内容,它会返回颜色集合。但是如果你通过baseColor,它将根据basedColor 生成hue 一组颜色。 hue 定义的基色为:red,yellow,green,cyan,blue & magenta。
用法
示例:1 - getRandomColors(10) 或 getRandomColors(10,'random') 或 getRandomColors(10,'anything besides Hue')
结果://(10) ["#C4AD05", "#B63DCB", "#22A9FE", "#59DCAC", "#986FFD", "#493E56", "#49693D", "#83029A", "#59E3C0", "#C6FB84"]
示例:2 - getRandomColors(10,'blue') //baseColor
结果://(10) ["hsl(240, 79%, 19%)", "hsl(240, 44%, 45%)", "hsl(240, 13%, 64%)", "hsl(240, 63%, 73%)", "hsl(240, 52%, 45%)", "hsl(240, 61%, 83%)", "hsl(240, 46%, 58%)", "hsl(240, 35%, 6%)", "hsl(240, 89%, 89%)", "hsl(240, 76%, 97%)"]
代码
function getRandomColors(len, baseColor = 'random') {
var colors = [];
var baseValue = getColorValue(baseColor);
var execFn = getExecFn(baseValue);
for (var i = 0; i < len; i++) {
colors.push(execFn());
}
return colors;
function getExecFn(baseColorValue) {
if (baseColorValue == -1) {
return getRandomColor;
}
else {
return hueSet;
}
}
function hueSet() {
h = baseValue;
s = Math.floor(Math.random() * 100);
l = Math.floor(Math.random() * 100);
return 'hsl(' + h + ', ' + s + '%, ' + l + '%)';
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function getColorValue(baseColor) {
switch (baseColor.toLowerCase()) {
case 'red':
return 0;
case 'yellow':
return 60;
case 'green':
return 120;
case 'cyan':
return 180;
case 'blue':
return 240;
case 'magenta':
return 300;
default:
return -1;
}
}
}