JS 颜色处理

159 阅读1分钟

常用处理方法

判断是否为十六进制颜色值
export const isHexColor=(color: string) =>{
  const reg = /^#([0-9a-fA-F]{3}|[0-9a-fA-f]{6})$/;
  return reg.test(color);
}
isHexColor("#ff0")// true
isHexColor("#ffffff")// true
RGB 颜色值转换为十六进制颜色值
 const rgbToHex=(r: number, g: number, b: number)=> {
  // tslint:disable-next-line:no-bitwise
  const hex = ((r << 16) | (g << 8) | b).toString(16);
  return '#' + new Array(Math.abs(hex.length - 7)).join('0') + hex;
}
 rgbToHex(255,255,255)//#ffffff

r, g, 和 b 需要在 [0, 255] 范围内

将 HEX 颜色转换为其 RGB 表示
 const hexToRGB=(hex: string)=> {
  let sHex = hex.toLowerCase();
  if (isHexColor(hex)) {
    if (sHex.length === 4) {
      let sColorNew = '#';
      for (let i = 1; i < 4; i += 1) {
        sColorNew += sHex.slice(i, i + 1).concat(sHex.slice(i, i + 1));
      }
      sHex = sColorNew;
    }
    const sColorChange: number[] = [];
    for (let i = 1; i < 7; i += 2) {
      sColorChange.push(parseInt('0x' + sHex.slice(i, i + 2)));
    }
    return 'RGB(' + sColorChange.join(',') + ')';
  }
  return sHex;
}
 hexToRGB('#f1f')//RGB(255,17,255)
检查颜色是否为深色(可用于设置字体颜色)
 const colorIsDark=(color: string)=> {
  if (!isHexColor(color)) return;
  const [r, g, b] = hexToRGB(color)
    .replace(/(?:(|)|rgb|RGB)*/g, '')
    .split(',')
    .map((item) => Number(item));
  return r * 0.299 + g * 0.578 + b * 0.114 < 192;
}
 colorIsDark('#f1ff1f')// false
设置颜色变深
const darken=(color: string, amount: number) =>{
  color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
  amount = Math.trunc((255 * amount) / 100);
  return `#${subtractLight(color.substring(0, 2), amount)}${subtractLight(
    color.substring(2, 4),
    amount,
  )}${subtractLight(color.substring(4, 6), amount)}`;
}
darken('#f1ff1f',20)//#becc00
设置颜色变浅
 const lighten=(color: string, amount: number)=> {
  color = color.indexOf('#') >= 0 ? color.substring(1, color.length) : color;
  amount = Math.trunc((255 * amount) / 100);
  return `#${addLight(color.substring(0, 2), amount)}${addLight(
    color.substring(2, 4),
    amount,
  )}${addLight(color.substring(4, 6), amount)}`;
}
 lighten('#f1ff1f',20)// #ffff52
设置R\G\B中的一种变浅
const addLight=(color: string, amount: number)=> {
  const cc = parseInt(color, 16) + amount;
  const c = cc > 255 ? 255 : cc;
  return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
}
addLight('0b0',20)//c4
addLight('0b',20)//1f
设置R\G\B中的一种变深
const subtractLight=(color: string, amount: number)=> {
  const cc = parseInt(color, 16) - amount;
  const c = cc < 0 ? 0 : cc;
  return c.toString(16).length > 1 ? c.toString(16) : `0${c.toString(16)}`;
}
subtractLight('0b',20)//00
subtractLight('0b0',20)//9c
计算 rgb 颜色的亮度
const luminance=(r: number, g: number, b: number) =>{
  const a = [r, g, b].map((v) => {
    v /= 255;
    return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
  });
  return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
luminance(255,255,255)//1
luminance(1,255,2)//0.715
计算两种 rgb 颜色之间的对比度
const contrast=(rgb1: string[], rgb2: number[])=> {
  return (
    (luminance(~~rgb1[0], ~~rgb1[1], ~~rgb1[2]) + 0.05) /
    (luminance(rgb2[0], rgb2[1], rgb2[2]) + 0.05)
  );
}
contrast(['12','23','36'],[12,23,36])//1
contrast(['121','211','136'],[12,23,36])//9.87
根据与背景的对比确定最佳文本颜色(黑色或白色)
 const calculateBestTextColor=(hexColor: string)=> {
  const rgbColor = hexToRGB(hexColor);
  const contrastWithBlack = contrast(rgbColor.split(','), [0, 0, 0]);
​
  return contrastWithBlack >= 12 ? '#000000' : '#FFFFFF';
}
 calculateBestTextColor('#fe0')// #000000
 calculateBestTextColor('#0a0a00')// #FFFFFFF

扫码_搜索联合传播样式-标准色版.png