根据一个颜色值转换标题颜色(文字、边框、背景)

154 阅读1分钟

根据后端传回的标签信息

截屏2023-01-13 15.29.51.png 截屏2023-01-13 15.50.37.png

根据该color值转换得出文字的颜色,边框的颜色,背景的颜色,实现标签不同颜色的展示效果  

后端传过来的值一般为HEX(16进制格式),要先将其转换为rgb格式

1、在utils文件夹中创建colorTransform.js/ts的文件(实现代码的组件式封装,注意高内聚低耦合)

vue2.0写法

module.exports.hexToRgb = hex => {
  const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);


  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : null;
};

vue3.0写法

export function hexToRgb (hex) {
    const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
    hex = hex.replace(shorthandRegex, (m, r, g, b) => r + r + g + g + b + b);
  
    const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? [parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)] : null;
  };

 

在所需要的文件中引入该js文件

import { hexToRgb } from '@/utils/colorTransform';

并在文件中创建函数实现颜色值的转换

//处理标签颜色
const adjust = (value, r0, r1, r2, r3) => {
  const mag = Math.abs(value - r0);
  const sgn = value < 0 ? -1 : 1;
  return (sgn * mag * (r3 - r2)) / (r1 - r0);
};


const label = (label) => {
  if (label) {
    const [r, g, b] = hexToRgb(label.color);
    const grayle = r * 0.23 + g * 0.7 + b * 0.07;
    const orign = `rgb(${r}, ${g}, ${b})`;
    const light = `rgb(${r * 0.1 + 255 * 0.9}, ${g * 0.1 + 255 * 0.9}, ${
      b * 0.1 + 255 * 0.9
    })`;
    const invert = `rgb(${r * 0.5 + 128 * 0.5}, ${g * 0.5 + 128 * 0.5}, ${
      b * 0.5 + 128 * 0.5
    })`;
    if (adjust(grayle, 0, 255, 0, 100) > 50) {
      return {
        bg: light,
        border: orign,
        text: invert,
      };
    } else {
      return {
        bg: light,
        border: orign,
        text: orign,
      };
    }
  }
  return null;
  };

最后对标签进行颜色值转换

 <span v-for="tag in item.labelList" :key="tag.id"
   :style="`background-color: ${label(tag)?.bg};border-color: ${label(tag)?.border};color: ${label(tag)?.text};`"
 >{{ tag.name }}</span>