已知16进制和透明度,使用JS语法求他们在一起的rgba。可以参考下面代码:

发布时间 2023-09-04 16:53:27作者: ZQ-404

事件起因:最近做的一个大转盘游戏页面样式编辑,背景透明度调整的时候,会导致字体一起变动,于是需要将背景演示的16进制和透明度一起转换成rgba。

 

function hexToRgba(hex, alpha) {
// 去掉可能包含的 "#" 符号
if (hex.startsWith("#")) {
hex = hex.slice(1);
}

// 解析16进制颜色值,并确保它是6个字符(3个分量)或8个字符(3个分量 + 透明度)
if (hex.length === 6 || hex.length === 8) {
// 如果是8个字符,提取前6个字符作为颜色部分
const colorPart = hex.length === 8 ? hex.slice(0, 6) : hex;
const red = parseInt(colorPart.slice(0, 2), 16);
const green = parseInt(colorPart.slice(2, 4), 16);
const blue = parseInt(colorPart.slice(4, 6), 16);

// 确保透明度在0到1之间
const alphaValue = Math.min(1, Math.max(0, alpha));

// 使用字符串插值构建RGBA颜色字符串
return `rgba(${red}, ${green}, ${blue}, ${alphaValue})`;
} else {
throw new Error('Invalid hex color format');
}
}

// 示例用法
const hexColor = '#FF0000';
const alpha = 0.5;

try {
const rgbaColor = hexToRgba(hexColor, alpha);
console.log(rgbaColor); // 输出 "rgba(255, 0, 0, 0.5)"
} catch (error) {
console.error(error.message); // 输出错误消息(如果16进制颜色格式无效)
}