我正在尝试找到一种可以将 RGB 或 RGBA 字符串转换为十六进制格式的方法。我找到了解决方案,但不是像方法 1 => rgbToHex 这样的一种方法,对于 RGBA rgbaToHex 我想将它们组合起来,这样它就可以返回 RGB 和 RGBA 的十六进制值
RGB方法:
// convert RGB color data to hex
function rgb2hex(r, g, b) {
if (r > 255 || g > 255 || b > 255)
throw "Invalid color component";
return ((r << 16) | (g << 8) | b).toString(16);
}
RGBA方法:
function rgba2hex(r, g, b, a) {
if (r > 255 || g > 255 || b > 255 || a > 255)
throw "Invalid color component";
return (256 + r).toString(16).substr(1) +((1 << 24) + (g << 16) | (b << 8) | a).toString(16).substr(1);
}
我想要什么:
//takes both RGB and RGBA and convert to HEX like #000000
// input will be string like this => rgb(0,0,0) or rgba(255,255,255, 0.5)
function anyToHex() {
return; // hex value
}
我创建了我的解决方案,它可以采用任何字符串 rgb 或 rgba,然后返回一个十六进制值 这是我的建议:
function componentToHex(c) {
var hex = c.toString(16);
return hex.length == 1 ? "0" + hex : hex;
}
function anytoHEX(string) {
rgb = string.substring(4, string.length-1).replace(/ /g, '').split(',');
R = rgb[0].replace("(", "");
G = rgb[1];
B = rgb[2];
return "#" + componentToHex(R) + componentToHex(G) + componentToHex(B);
}
console.log(anytoHEX('rgba(0,0,0,0)'));
最佳答案
您可以将其作为包装器,并根据传递的参数调用该函数
//takes both RGB and RGBA and convert to HEX like #000000
// input will be string like this => rgb(0,0,0) or rgba(255,255,255, 0.5)
function anyToHex(r, g, b, a) {
if(a === undefined){
return rgb2hex(r, g, b);
}
return rgba2hex(r, g, b, a);
}
关于javascript - RGBA 和 RGB 转十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50890731/