一、生成同一色系有深入浅的颜色
color:'rgba(0,66,125,1)' num:5
export function generateLighterColors(color, num) {
let r: number, g: number, b: number, a: number;
if (color.startsWith('#')) {
color = color.slice(1);
if (color.length === 3) {
color = color
.split('')
.map((c) => c + c)
.join('');
}
r = parseInt(color.substr(0, 2), 16);
g = parseInt(color.substr(2, 2), 16);
b = parseInt(color.substr(4, 2), 16);
} else if (color.startsWith('rgba')) {
const rgba = color.match(/\d+(\.\d+)?/g);
r = parseInt(rgba![0], 10);
g = parseInt(rgba![1], 10);
b = parseInt(rgba![2], 10);
a = parseFloat(rgba![3]);
} else {
throw new Error('Invalid color format');
}
const lighterColors: string[] = [];
const nums = num || 1;
for (let i = 0; i < nums; i++) {
const factor = 1 + i * (nums / 10); // 调整因子,用于控制颜色变浅程度
const newR = Math.round(r * factor);
const newG = Math.round(g * factor);
const newB = Math.round(b * factor);
// @ts-ignore
const rgba = a !== undefined ? `rgba(${newR}, ${newG}, ${newB}, ${a * (1 - i * 0.1)})` : `rgba(${newR}, ${newG}, ${newB})`;
lighterColors.push(rgba);
}
return lighterColors;
}
二、同一个颜色指定变浅多少
export function lightenHexColor(hexColor, percentage) {
// 确保百分比在0-100之间
percentage = Math.max(0, Math.min(100, percentage));
// 转换为RGB
let r = parseInt(hexColor.slice(1, 3), 16);
let g = parseInt(hexColor.slice(3, 5), 16);
let b = parseInt(hexColor.slice(5, 7), 16);
// 计算增加的亮度量
const increase = (255 * percentage) / 100;
// 增加亮度并确保不超过255
r = Math.min(255, r + increase);
g = Math.min(255, g + increase);
b = Math.min(255, b + increase);
// 转换回16进制并返回
const color = '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1).toUpperCase().padStart(6, '0');
return color.substring(0, 7);
}
三、随机生成不重复颜色
export function generateDifferentColors(randomColorArray) {
const randomColor = getRandomColor();
if (randomColorArray?.length) {
const hasColor = randomColorArray?.find((item) => item === randomColor);
if (hasColor) {
generateDifferentColors(randomColorArray);
} else {
randomColorArray.push(randomColor);
}
} else {
randomColorArray.push(randomColor);
}
return randomColor;
}
四、生成随机hex颜色
export default function getRandomColor() {
let str = '#';
const arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
for (let i = 0; i < 6; i++) {
const cryptoArray = new Uint32Array(1);
window.crypto.getRandomValues(cryptoArray);
const randomValue = cryptoArray[0];
const num = randomValue % 16;
str += arr[num];
}
return str;
}