js生成一组颜色数组 要求116进制形式2浅色3颜色之间尽量区分而不要相似4数组长度由调用者传入
function generateColors(num) { const colors = []; const base = ['00', '33', '66', '99', 'CC', 'FF']; let r, g, b;
for (let i = 0; i < num; i++) { // 生成红、绿、蓝三个分量的值 r = base[Math.floor(Math.random() * base.length)]; g = base[Math.floor(Math.random() * base.length)]; b = base[Math.floor(Math.random() * base.length)];
// 组合成16进制颜色值
const color = '#' + r + g + b;
// 判断颜色是否已存在
if (!colors.includes(color)) {
colors.push(color);
} else {
i--;
}
}
return colors; }
// 示例代码 const colors = generateColors(10); console.log(colors); // ['#3366CC', '#66CC33', '#FF9933', '#FFCC99', '#666699', '#99CC66', '#CCFF33', '#33CCCC', '#FF6666', '#99CC99'
原文地址: https://www.cveoy.top/t/topic/e0as 著作权归作者所有。请勿转载和采集!