如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
如何将颜色在RGB格式转换为十六进制格式,反之亦然?
例如,将'#0080C0'转换为(0,128,192)。
当前回答
看起来你在寻找这样的东西:
function hexstr(number) {
var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var low = number & 0xf;
var high = (number >> 4) & 0xf;
return "" + chars[high] + chars[low];
}
function rgb2hex(r, g, b) {
return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}
其他回答
hexToRgb的另一个版本:
function hexToRgb(hex) {
var bigint = parseInt(hex, 16);
var r = (bigint >> 16) & 255;
var g = (bigint >> 8) & 255;
var b = bigint & 255;
return r + "," + g + "," + b;
}
编辑:3/28/2017 这是另一种似乎更快的方法
function hexToRgbNew(hex) {
var arrBuff = new ArrayBuffer(4);
var vw = new DataView(arrBuff);
vw.setUint32(0,parseInt(hex, 16),false);
var arrByte = new Uint8Array(arrBuff);
return arrByte[1] + "," + arrByte[2] + "," + arrByte[3];
}
编辑:8/11/2017 经过更多测试后,上面的新方法并没有更快:(。虽然这是一种有趣的替代方式。
不可变和人类可理解的版本,没有任何位魔法:
循环数组 使用Math.min()和Math.max()对值< 0或值> 255进行归一化 使用String.toString()将数字转换为十六进制符号 将前导零和修饰值附加到两个字符 将映射值连接到字符串
function rgbToHex(r, g, b) {
return [r, g, b]
.map(color => {
const normalizedColor = Math.max(0, Math.min(255, color));
const hexColor = normalizedColor.toString(16);
return `0${hexColor}`.slice(-2);
})
.join("");
}
是的,它不会像位操作符那样性能好,但更可读和不可变,所以它不会修改任何输入
短箭头函数
对于那些重视短箭头功能的人。
Hex2rgb
大卫的答案的箭头函数版本
const hex2rgb = h => [(x=parseInt(h,16)) >> 16 & 255,x >> 8 & 255, x & 255];
一个更灵活的解决方案,支持短十六进制或哈希#
const hex2rgb = h => {
if(h[0] == '#') {h = h.slice(1)};
if(h.length <= 3) {h = h[0]+h[0]+h[1]+h[1]+h[2]+h[2]};
h = parseInt(h,16);
return [h >> 16 & 255,h >> 8 & 255, h & 255];
};
Rgb2hex
const rgb2hex = (r,g,b) => ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
看起来你在寻找这样的东西:
function hexstr(number) {
var chars = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
var low = number & 0xf;
var high = (number >> 4) & 0xf;
return "" + chars[high] + chars[low];
}
function rgb2hex(r, g, b) {
return "#" + hexstr(r) + hexstr(g) + hexstr(b);
}
这可以用于从计算样式属性中获取颜色:
function rgbToHex(color) {
color = ""+ color;
if (!color || color.indexOf("rgb") < 0) {
return;
}
if (color.charAt(0) == "#") {
return color;
}
var nums = /(.*?)rgb\((\d+),\s*(\d+),\s*(\d+)\)/i.exec(color),
r = parseInt(nums[2], 10).toString(16),
g = parseInt(nums[3], 10).toString(16),
b = parseInt(nums[4], 10).toString(16);
return "#"+ (
(r.length == 1 ? "0"+ r : r) +
(g.length == 1 ? "0"+ g : g) +
(b.length == 1 ? "0"+ b : b)
);
}
// not computed
<div style="color: #4d93bc; border: 1px solid red;">...</div>
// computed
<div style="color: rgb(77, 147, 188); border: 1px solid rgb(255, 0, 0);">...</div>
console.log( rgbToHex(color) ) // #4d93bc
console.log( rgbToHex(borderTopColor) ) // #ff0000
裁判:https://github.com/k-gun/so/blob/master/so_util.js