【前端】js方法 hex转rgba

【前端】js方法 hex转rgba

//hex转rgba

javascript 复制代码
 //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() + ")";
};


//用法

hex2Rgba('#ffffff', 1)
//'rgba(255,255,255,1)'
javascript 复制代码
来自u-charts.js
// hex 转 rgba
function hexToRgb(hexValue, opc) {
  var rgx = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  var hex = hexValue.replace(rgx, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });
  var rgb = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  if(!rgb){
	  return hexValue;
  }
  var r = parseInt(rgb[1], 16);
  var g = parseInt(rgb[2], 16);
  var b = parseInt(rgb[3], 16);
  return 'rgba(' + r + ',' + g + ',' + b + ',' + opc + ')';
}

十进制转hex

javascript 复制代码
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;
};
 
// 十进制转hex
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;
}
相关推荐
许彰午10 小时前
14_Java泛型完全指南
java·windows·python
Snasph10 小时前
GNU Make 用户手册(中文版)
服务器·算法·gnu
智慧物业老杨10 小时前
司法绿色通道下的物业纠纷数智化解决方案——基于“三优先“机制的全流程技术落地实践
java·django
2601_9611940210 小时前
2026初级会计实务公式总结大全|计算题公式手册PDF
java·spring·eclipse·pdf·tomcat·hibernate
做个文艺程序员10 小时前
第1篇:K8s 核心概念精讲:Pod、Deployment、Service 与 Namespace——Java 开发者快速上手指南
java·云原生·容器·kubernetes·容器编排
广州灵眸科技有限公司10 小时前
瑞芯微RV1126B开发板(EASY-EAI-PI2) Easy-Eai编译环境准备与更新
服务器·前端·人工智能·python·深度学习
Esaka_Forever11 小时前
uv init 完整用法(Python 最快包管理器)
服务器·python·uv
溜达的大象11 小时前
服务器挂了等用户报障?我用Prometheus搭了一套监控告警,服务器出状况第一时间通知我
服务器·php·prometheus
万少11 小时前
我把 Kimi 接进微信,几分钟做了个随手出图助手
前端