【前端】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;
}
相关推荐
菜鸟233号1 分钟前
力扣377 组合总和 Ⅳ java实现
java·数据结构·算法·leetcode
耶耶耶耶耶~5 分钟前
arch linux 安装
linux·运维·服务器
星火开发设计30 分钟前
Java面向对象三大特性:封装、继承与多态的深度解析及实战
java·开发语言·microsoft·多态·继承·面向对象·封装
ashcn200137 分钟前
linux 制作一个自解压文件
linux·运维·服务器
hhzz38 分钟前
EasyPoi的核心映射工具:@Excel注解详解
java·服务器·excel·springboot·easypoi
Joe5561 小时前
vue2 + antDesign 下拉框限制只能选择2个
服务器·前端·javascript
码农小卡拉1 小时前
数据库:主键 VS 唯一索引 区别详解
java·数据库·sql
何妨呀~1 小时前
Keepalived+Haproxy高可用集群实验
linux·服务器·网络
e***98571 小时前
Java性能优化实战:从原理到案例
java·开发语言·性能优化
float_六七1 小时前
设备分配核心数据结构全解析
linux·服务器·数据结构