一、Js 實作顔色值轉換處理
js實作 十六進制顔色值轉RGB顔色值
js實作 RGB顔色值 轉 十六進制顔色值
var colorChange = {
rgbToHex: function (val) { //RGB(A)顔色轉換為HEX十六進制的顔色值
var r, g, b, a,
regRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/, //判斷rgb顔色值格式的正規表達式,如rgba(255,20,10,.54)
rsa = val.replace(/\s+/g, '').match(regRgba);
if (!!rsa) {
r = parseInt(rsa[1]).toString(16);
r = r.length == 1 ? '0' + r : r;
g = (+rsa[2]).toString(16);
g = g.length == 1 ? '0' + g : g;
b = (+rsa[3]).toString(16);
b = b.length == 1 ? '0' + b : b;
a = (+(rsa[5] ? rsa[5] : 1)) * 100;
return { hex: '#' + r + g + b, r: parseInt(r, 16), g: parseInt(g, 16), b: parseInt(b, 16), alpha: Math.ceil(a) };
} else {
return { hex: '無效', alpha: 100 };
}
},
hexToRgb: function (val) { //HEX十六進制顔色值轉換為RGB(A)顔色值
// 16進制顔色值的正則
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 把顔色值變成小寫
var color = val.toLowerCase();
var result = '';
if (reg.test(color)) {
// 如果隻有三位的值,需變成六位,如:#fff => #ffffff
if (color.length === 4) {
var colorNew = "#";
for (var i = 1; i < 4; i += 1) {
colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
}
color = colorNew;
}
// 處理六位的顔色值,轉為RGB
var colorChange = [];
for (var i = 1; i < 7; i += 2) {
colorChange.push(parseInt("0x" + color.slice(i, i + 2)));
}
result = "rgb(" + colorChange.join(",") + ")";
return { rgb: result, r: colorChange[0], g: colorChange[1], b: colorChange[2] };
} else {
result = '無效';
return { rgb: result };
}
}
};
測試:
console.info(colorChange.rgbToHex('rgb(155,10,20)'));
console.info(colorChange.rgbToHex('rgb(155,10,20,0.5)'));
console.info(colorChange.hexToRgb('#ff0000'));
更多: