根据字母转换生成字体颜色和背景色

203 阅读1分钟
// 使用HSV转RGB算法得到颜色值
const hsvToRgb = (h: number, s: number, v: number): string => {
  let r;
  let g;
  let b;
  const i = Math.floor(h * 6);
  const f = h * 6 - i;
  const p = v * (1 - s);
  const q = v * (1 - f * s);
  const t = v * (1 - (1 - f) * s);

  switch (i % 6) {
    case 0:
      r = v;
      g = t;
      b = p;
      break;
    case 1:
      r = q;
      g = v;
      b = p;
      break;
    case 2:
      r = p;
      g = v;
      b = t;
      break;
    case 3:
      r = p;
      g = q;
      b = v;
      break;
    case 4:
      r = t;
      g = p;
      b = v;
      break;
    case 5:
      r = v;
      g = p;
      b = q;
      break;
  }

  return `rgb(${Math.round(r * 255)}, ${Math.round(g * 255)}, ${Math.round(
    b * 255
  )})`;
};

export const hashToBgColor = (char: string = ''): string => {
  // 得到背景颜色
  let hash = 0;
  for (let i = 0; i < char.length; i++) {
    hash = char.charCodeAt(i) + ((hash << 5) - hash);
  }

  return `hsl(${hash % 360}, 50%, 90%)`;
};

export const hashToColor = (char: string = ''): string => {
  // 得到字体颜色
  // 简单的哈希函数示例,用于将字符转换为颜色
  let hash = 0;
  for (let i = 0; i < char.length; i++) {
    hash = char.charCodeAt(i) + ((hash << 5) - hash);
  }

  // 将哈希值映射到0-360度区间,用于HSV色彩模式中的色调部分
  const hue = hash % 360;

  const saturation = 0.6; // 饱和度
  const value = 0.7; // 明度

  return hsvToRgb(hue / 360, saturation, value);
};