JavaScript 生成浅色 16 进制颜色数组:均匀分布、避免相似
function generateColorsArray(length) { const colors = []; let count = 0; while (colors.length < length) { // 生成随机的 RGB 值 const r = Math.floor(Math.random() * 256); const g = Math.floor(Math.random() * 256); const b = Math.floor(Math.random() * 256); // 计算亮度 const brightness = (r * 299 + g * 587 + b * 114) / 1000; // 如果亮度太暗,跳过这个颜色 if (brightness < 150) continue; // 计算颜色距离 let distance = Infinity; for (let i = 0; i < colors.length; i++) { const color = colors[i]; const rDiff = color.r - r; const gDiff = color.g - g; const bDiff = color.b - b; const colorDistance = Math.sqrt(rDiff * rDiff + gDiff * gDiff + bDiff * bDiff); if (colorDistance < distance) { distance = colorDistance; } } // 如果颜色距离太近,跳过这个颜色 if (distance < 80) continue; // 将 RGB 值转换成 16 进制字符串 const hex = ((r << 16) | (g << 8) | b).toString(16); const hexColor = '#' + hex.padStart(6, '0'); // 将颜色添加到数组中 colors.push({ hex: hexColor, r, g, b }); count++; // 如果尝试次数超过 1000 次,则退出循环,避免死循环 if (count > 1000) break; } return colors.map(color => color.hex); }
// 示例: generateColorsArray(5); // 返回一个由 5 个颜色值组成的数组
原文地址: http://www.cveoy.top/t/topic/n0QP 著作权归作者所有。请勿转载和采集!