【前端】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;
}
相关推荐
前端小趴菜0512 分钟前
React-React.memo-props比较机制
前端·javascript·react.js
摸鱼仙人~1 小时前
styled-components:现代React样式解决方案
前端·react.js·前端框架
kangkang-1 小时前
PC端基于SpringBoot架构控制无人机(三):系统架构设计
java·架构·无人机
段帅龙呀1 小时前
Redis构建缓存服务器
服务器·redis·缓存
乌鸦不像写字台2 小时前
【docker部署】在服务器上使用docker
服务器·docker·容器
sasaraku.2 小时前
serviceWorker缓存资源
前端
RadiumAg3 小时前
记一道有趣的面试题
前端·javascript
yangzhi_emo3 小时前
ES6笔记2
开发语言·前端·javascript
界面开发小八哥3 小时前
「Java EE开发指南」如何用MyEclipse创建一个WEB项目?(三)
java·ide·java-ee·myeclipse
yanlele3 小时前
我用爬虫抓取了 25 年 5 月掘金热门面试文章
前端·javascript·面试