JS 颜色RGB转换为16进制 相互转换 方法

/*RGB转换为16进制*/
const colorRgbToHex = (rgbStr: string) => {
  //十六进制颜色值的正则表达式
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8}|[0-9a-fA-f]{6}[0-9]{2})$/;
  if (reg.test(rgbStr)) {
    return rgbStr
  } else {
    const rgbArray = rgbStr.replace(/(?:\(|\)|rgba|rgb|RGBA|RGB)*/g, "").split(",");
    let strHex = "#";
  	  for (let i = 0; i < rgbArray.length; i++) {
      if (i !== 3) {
        if (rgbArray[i] == "0") {
          strHex += "00"
        } else {
              let newItem = Number(rgbArray[i]).toString(16)
              if (newItem.length < 2){
                newItem = "0" + newItem
              }
              strHex += newItem
        }
        } else {
        strHex += rgbArray[i] == "0" ? "" : Number(rgbArray[i]) * 100
      }
    }
   	 return strHex;
  }
}

/*16进制转换为RGB*/
const colorHexToRgb = (hexStr: string, opacity?: boolean) => {
  //rgb颜色值的正则表达式
  const reg = /^(rgba|rgb|RGBA|RGB)\([\s]*[0-9]+[\s]*,[\s]*[0-9]+[\s]*,[\s]*[0-9]+[\s]*(,[\s]*[0-9.]+[\s]*)*\)$/;
  if (reg.test(hexStr)) {
    return hexStr
  } else {
    hexStr = hexStr.toLowerCase()
    if (hexStr.length === 4) {
      let colorNew = "#";
      for (leti = 1; i < 4; i += 1) {
        const str = hexStr.slice(i, i + 1);
        colorNew += str + str;
      }
      hexStr = colorNew;
    }
    const rgbArray = [];
    for (let i = 1; i < hexStr.length; i += 2) {
      if (i < 7) {
        rgbArray.push(parseInt("0x" + hexStr.slice(i, i + 2)));
      }
      if (i >= 7 && opacity) {
        const str = hexStr.slice(i, i + 2)
        rgbArray.push(/^[a-f0-9]{2}$/.test(str) ? parseInt(`0x${str}`) / 255 : (Number(str) / 100).toString())
      }
    }
    return (opacity ? "rgba(" : "rgb(") + rgbArray.join(",") + ")";
  }
}

你可能感兴趣的:(JS,javascript,前端)