目前我有这个代码生成随机颜色:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<input data-bind="textInput: query, valueUpdate: 'keyup', event: { focus: onFocus }" type="text" placeholder="What are you looking for?" />
<select id="searchCategory" data-bind="options: availableCategories, value: selectedCategory, optionsCaption: 'Search by Category'"></select>
<select id="searchTCA" data-bind="options: availableTcaMethods, value: selectedTcaMethod, optionsCaption: 'Search by TCA Method'"></select>
但我想要的是产生一种随机的“色调”颜色,我应该添加/改变什么才能让它发挥作用......?
答案 0 :(得分:1)
如果您可以使用hsl()
作为颜色,那将是最简单的。您可以将色调设置为随机值,并将饱和度和亮度设置为常量(或小范围)。
如果你需要rgb字符串,你可以使用here和其他地方的标准HSL-> RGB转换来制作rgb字符串。
let [sat, lightness] = [.6, .8]
let container = document.getElementById("colors")
for (let i = 0; i < 12; i++) {
let hue = Math.random()
let block = document.createElement('div');
block.className = 'colorbrick';
block.style.backgroundColor = hslToRgb(hue, sat,lightness);
container.appendChild(block)
}
function hslToRgb(h, s, l) {
let r, g, b;
if (s == 0) {
r = g = b = l;
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1 / 3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1 / 3);
}
return "#" + [r * 255, g * 255, b * 255].map(c => Math.floor(c).toString(16)).join('');
};
.colorbrick {
display: inline-block;
width: 80px;
height: 80px;
margin: 6px;
}
<div id="colors">
</div>