Skip to content

字符串转颜色值

字符串转哈希(数字)

javascript
function hashCode(str) {
  // str to hash
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  return hash;
}

let string = "https://www.zhengxinonly.com";
console.log(hashCode(string));
// 2379989682

哈希转颜色值

javascript
function intToRGB(i) {
  let c = (i & 0x00ffffff).toString(16).toUpperCase();

  return "00000".substring(0, 6 - c.length) + c;
}

console.log(intToRGB(hashCode(string)));
// 'DBC2B2'

获取不同程度的颜色值

javascript
const hexToRgb = (str) => {
  let hexs = null;
  let reg = /^\#?[0-9A-Fa-f]{6}$/;
  if (!reg.test(str)) return alert("色值不正确");
  str = str.replace("#", ""); // 去掉 #
  hexs = str.match(/../g); // 切割成数组 409EFF => ['40','9E','FF']
  // 将切割的色值转换为 16 进制
  for (let i = 0; i < hexs.length; i++) hexs[i] = parseInt(hexs[i], 16);
  return hexs; // 返回 rgb 色值 [64, 158, 255]
};

const getLightColor = (color, level) => {
  let rgb = hexToRgb(color);
  let hexs = "";

  // 循环对色值进行调整
  for (let i = 0; i < 3; i++) {
    rgb[i] = Math.floor((255 - rgb[i]) * level + rgb[i]); // 始终保持在 0-255 之间
    hexs += rgb[i].toString(16);
  }
  return hexs; // [159, 206, 255]
};

console.log(stringToHexColor(string));
// 'DBC2B2'

console.log(getLightColor("#" + stringToHexColor(string), 0.8));
// 'f7f2ef'

参考

hex 和 rgb 色值转换 - 色彩加深减淡