如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
从HEX转换为RGB,其中RGB是0到1范围内的浮点值:
#FFAA22→{r: 0.5, g: 0, b:1}
我改编了@Tim Down的回答:
function convertRange(value,oldMin,oldMax,newMin,newMax) {
return (Math.round(((((value - oldMin) * (newMax - newMin)) / (oldMax - oldMin)) + newMin) * 10000)/10000)
}
function hexToRgbFloat(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: convertRange(parseInt(result[1],16), 0, 255, 0, 1),
g: convertRange(parseInt(result[2],16), 0, 255, 0, 1),
b: convertRange(parseInt(result[3],16), 0, 255, 0, 1)
} : null;
}
console.log(hexToRgbFloat("#FFAA22")) // {r: 1, g: 0.6667, b: 0.1333}
其他回答
我发现了这个,因为我认为它非常直截了当,有验证测试和支持alpha值(可选),这将适合这种情况。
只要注释掉regex行,如果你知道你在做什么,它会快一点。
function hexToRGBA(hex, alpha){
hex = (""+hex).trim().replace(/#/g,""); //trim and remove any leading # if there (supports number values as well)
if (!/^(?:[0-9a-fA-F]{3}){1,2}$/.test(hex)) throw ("not a valid hex string"); //Regex Validator
if (hex.length==3){hex=hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2]} //support short form
var b_int = parseInt(hex, 16);
return "rgba("+[
(b_int >> 16) & 255, //R
(b_int >> 8) & 255, //G
b_int & 255, //B
alpha || 1 //add alpha if is set
].join(",")+")";
}
当你在3D环境中工作时(webGL, ThreeJS),你有时需要为网格的不同面创建3个值,基本的一个(主色),一个浅一点的和一个深一点的:
material.color.set( 0x660000, 0xff0000, 0xff6666 ); // red cube
我们可以从主RBG颜色创建这3个值:255,0,0
function rgbToHex(rgb) {
var hex = Number(rgb).toString(16);
if (hex.length < 2) {
hex = "0" + hex;
}
return hex;
};
function convertToHex(r,g,b) {
var fact = 100; // contrast
var code = '0x';
// main color
var r_hexa = rgbToHex(r);
var g_hexa = rgbToHex(g);
var b_hexa = rgbToHex(b);
// lighter
var r_light = rgbToHex(Math.floor(r+((1-(r/255))*fact)));
var g_light = rgbToHex(Math.floor(g+((1-(g/255))*fact)));
var b_light = rgbToHex(Math.floor(b+((1-(b/255))*fact)));
// darker
var r_dark = rgbToHex(Math.floor(r-((r/255)*(fact*1.5)))); // increase contrast
var g_dark = rgbToHex(Math.floor(g-((g/255)*(fact*1.5))));
var b_dark = rgbToHex(Math.floor(b-((b/255)*(fact*1.5))));
var hexa = code+r_hexa+g_hexa+b_hexa;
var light = code+r_light+g_light+b_light;
var dark = code+r_dark+g_dark+b_dark;
console.log('HEXs -> '+dark+" + "+hexa+" + "+light)
var colors = [dark, hexa, light];
return colors;
}
在你的ThreeJS代码中简单地写:
var material = new THREE.MeshLambertMaterial();
var c = convertToHex(255,0,0); // red cube needed
material.color.set( Number(c[0]), Number(c[1]), Number(c[2]) );
结果:
// dark normal light
convertToHex(255,255,255) HEXs -> 0x696969 + 0xffffff + 0xffffff
convertToHex(255,0,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(255,127,0) HEXs -> 0x690000 + 0xff0000 + 0xff6464
convertToHex(100,100,100) HEXs -> 0x292929 + 0x646464 + 0xa0a0a0
convertToHex(10,10,10) HEXs -> 0x040404 + 0x0a0a0a + 0x6a6a6a
一个完全不同的方法转换十六进制颜色代码到RGB没有正则表达式
它根据字符串长度处理#FFF和#FFFFFF格式。它从字符串的开头删除#,并将字符串的每个字符分割并将其转换为base10,并将其添加到其位置的相应索引中。
//Algorithm of hex to rgb conversion in ES5 function hex2rgbSimple(str){ str = str.replace('#', ''); return str.split('').reduce(function(result, char, index, array){ var j = parseInt(index * 3/array.length); var number = parseInt(char, 16); result[j] = (array.length == 3? number : result[j]) * 16 + number; return result; },[0,0,0]); } //Same code in ES6 hex2rgb = str => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]); //hex to RGBA conversion hex2rgba = (str, a) => str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0,a||1]); //hex to standard RGB conversion hex2rgbStandard = str => `RGB(${str.replace('#','').split('').reduce((r,c,i,{length: l},j,n)=>(j=parseInt(i*3/l),n=parseInt(c,16),r[j]=(l==3?n:r[j])*16+n,r),[0,0,0]).join(',')})`; console.log(hex2rgb('#aebece')); console.log(hex2rgbSimple('#aebece')); console.log(hex2rgb('#aabbcc')); console.log(hex2rgb('#abc')); console.log(hex2rgba('#abc', 0.7)); console.log(hex2rgbStandard('#abc'));
Tim Down给出的最高评级的答案提供了我所能看到的转换为RGB的最佳解决方案。我更喜欢这个十六进制转换的解决方案,因为它为转换到十六进制提供了最简洁的边界检查和零填充。
function RGBtoHex (red, green, blue) {
red = Math.max(0, Math.min(~~red, 255));
green = Math.max(0, Math.min(~~green, 255));
blue = Math.max(0, Math.min(~~blue, 255));
return '#' + ('00000' + (red << 16 | green << 8 | blue).toString(16)).slice(-6);
};
左移'<<'和或'|'操作符的使用也使这成为一个有趣的解决方案。
我假设您指的是html风格的十六进制符号,即#rrggbb。你的代码几乎是正确的,只是顺序颠倒了。它应该是:
var decColor = red * 65536 + green * 256 + blue;
此外,使用位移位可能会让它更容易阅读:
var decColor = (red << 16) + (green << 8) + blue;