例如,将rgba(0,0,0,1)
转换为4278190080
(0xFF000000
的结果)。
答案 0 :(得分:2)
然后简单地移动或。您还可以根据需要使用乘法然后加法。
[:punct:]
答案 1 :(得分:0)
我问这个问题是因为例如给定颜色,将颜色#4286F4转换为0xFF4286F4不会呈现相同的颜色。
对我来说很傻,我认为0xFFFFFFFF是按Alpha(不透明度),红色,绿色,蓝色的顺序形成的。但是我发现它的顺序代表Alpha,Blue,Green,Red。因此将#4286F4转换为给定格式将为0xFFF48642。
答案 2 :(得分:0)
如果您需要的话,我也可以使用此CSS颜色字符串作为Int32函数。
虽然没有使用hsl
或其他颜色格式。
// Convert css color to Int32
function color2hex(text){
let test, r = 0, g = 0, b = 0, a = 0;
if(test = /^rgba\(\s{0,}(\d+)\s{0,},\s{0,}(\d+)\s{0,},\s{0,}(\d+)\s{0,}\,\s{0,}([\d\.]+)\s{0,}\)$/g.exec(text)){
r = test[1];
g = test[2];
b = test[3];
a = Math.floor(test[4] * 0xff);
}else if(test = /^rgb\(\s{0,}(\d+)\s{0,},\s{0,}(\d+)\s{0,},\s{0,}(\d+)\s{0,}\)$/g.exec(text)){
r = test[1];
g = test[2];
b = test[3];
a = 0xff;
}else if(test = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/g.exec(text)){
r = parseInt(test[1], 16);
g = parseInt(test[2], 16);
b = parseInt(test[3], 16);
a = parseInt(test[4], 16);
}else if(test = /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/g.exec(text)){
r = parseInt(test[1], 16);
g = parseInt(test[2], 16);
b = parseInt(test[3], 16);
a = 0xff;
}else if(test = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/g.exec(text)){
r = parseInt(test[1] + '' + test[1], 16);
g = parseInt(test[2] + '' + test[2], 16);
b = parseInt(test[3] + '' + test[3], 16);
a = parseInt(test[4] + '' + test[4], 16);
}else if(test = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/g.exec(text)){
r = parseInt(test[1] + '' + test[1], 16);
g = parseInt(test[2] + '' + test[2], 16);
b = parseInt(test[3] + '' + test[3], 16);
a = 0xff;
}
return (a << 24 | r << 16 | g << 8 | b) >>> 0;
}
// Testing
document.write(color2hex('rgba(255, 0, 0, 1)').toString(16));
document.write('<br>');
document.write(color2hex('rgb(255,0,0)').toString(16));
document.write('<br>');
document.write(color2hex('#ff0000ff').toString(16));
document.write('<br>');
document.write(color2hex('#ff0000').toString(16));
document.write('<br>');
document.write(color2hex('#f00f').toString(16));
document.write('<br>');
document.write(color2hex('#f00').toString(16));
答案 3 :(得分:0)
function rgba(red,green,blue,trans){
let hex='#';
red=Number(red).toString(16);
if(red.length<2){ // if one digit need to append 0 infront
hex+='0'+red;
}
else{
hex+=red;
}
green=Number(green).toString(16);
if(green.length<2){
hex+='0'+green;
}
else{
hex+=green;
}
blue=Number(blue).toString(16);
if(blue.length<2){
hex+='0'+blue;
}
else{
hex+=blue;
}
trans=Number(trans*255).toString(16);
trans=trans.replace(/\..*/,'');
if(red.length<2){
hex+='0'+trans;
}
else{
hex+=trans;
}
return hex;
}
console.log(rgba(0,0,0,1));//#0000000ff
console.log(rgba(255,255,255,.5))//#ffffff7f
console.log(rgba(151,12,55,.89))//#970c37e2
RBGA具有红色,绿色和蓝色
所有RGB的范围是0到255 但是透明度是0到1 check here in mdn,因此我们需要特别注意,只需将1转换为255
我在chrome上测试了其预期的工作