随笔 - 50  文章 - 0  评论 - 1  阅读 - 86920

js rgba颜色转换

复制代码
// hex转rgba第一种
const hex2Rgb = (hexValue, alpha = 1) => {
  const rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  const hex = hexValue.replace(rgx, (m, r, g, b) => r + r + g + g + b + b);
  const rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if (!rgb) {
    return hexValue;
  }
  const r = parseInt(rgb[1], 16),
    g = parseInt(rgb[2], 16),
    b = parseInt(rgb[3], 16);
  return `rgba(${r},${g},${b},${alpha})`;
};
// hex转rgba第二种
const hex2Rgba = (bgColor, alpha = 1) => {
  let color = bgColor.slice(1); // 去掉'#'号
  let rgba = [
    parseInt("0x" + color.slice(0, 2)),
    parseInt("0x" + color.slice(2, 4)),
    parseInt("0x" + color.slice(4, 6)),
    alpha
  ];
  return "rgba(" + rgba.toString() + ")";
};
//十进制转hex
const getred = (color) => {
  const red = (color & 0xff0000) >> 16;
  return red;
};

const getgreen = (color) => {
  const green = (color & 0x00ff00) >> 8;
  return green;
};

const getblue = (color) => {
  const blue = color & 0x0000ff;
  return blue;
};
const Rgb2Hex = (color) => {=
  const r = getred(color);
  const g = getgreen(color);
  const b = getblue(color);
  const hex = "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  return hex;
}
复制代码

改造成自己想用的函数

复制代码
export const hex2Rgb = (hexValue, alpha = 1) => {
  const regex = /^#([0-9A-Fa-f]{6}),(?:\d+(?:\.\d*)?|\.\d+)$/;
  const match = regex.exec(hexValue);
  // console.log(match);
  if (match) (hexValue = `#${match[1]}`) && (alpha = match[0].split(",")[1]);

  const rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  const hex = hexValue.replace(rgx, (m, r, g, b) => r + r + g + g + b + b);
  const rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if (!rgb) return hexValue;
  const r = parseInt(rgb[1], 16),
    g = parseInt(rgb[2], 16),
    b = parseInt(rgb[3], 16);
  return `rgba(${r},${g},${b},${alpha})`;
};
复制代码

使用方法

hex2Rgb(`#FFFFFF,.5`)
//或者
hex2Rgb(`#FFFFFF`,0.5)

 

参考:https://blog.csdn.net/a460550542/article/details/127685094

posted on   写最骚的代码  阅读(1081)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示