1. 颜色转换
// 颜色转换
const colorChange = {
rgbToHex(val: string) {
// RGB(A)颜色转换为HEX十六进制的颜色值
let r;
let g;
let b;
let a;
const regRgba = /rgba?\((\d{1,3}),(\d{1,3}),(\d{1,3})(,([.\d]+))?\)/; // 判断rgb颜色值格式的正则表达式,如rgba(255,20,10,.54)
const rsa = val.replace(/\s+/g, '').match(regRgba);
if (rsa) {
// eslint-disable-next-line radix
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) };
}
return { hex: '无效', alpha: 100 };
},
hexToRgb(val: string) {
// HEX十六进制颜色值转换为RGB(A)颜色值
// 16进制颜色值的正则
const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 把颜色值变成小写
let color = val.toLowerCase();
let result = '';
if (reg.test(color)) {
// 如果只有三位的值,需变成六位,如:#fff => #ffffff
if (color.length === 4) {
let colorNew = '#';
for (let i = 1; i < 4; i += 1) {
colorNew += color.slice(i, i + 1).concat(color.slice(i, i + 1));
}
color = colorNew;
}
// 处理六位的颜色值,转为RGB
const changeed = [];
for (let i = 1; i < 7; i += 2) {
// eslint-disable-next-line radix
changeed.push(parseInt(`0x${color.slice(i, i + 2)}`));
}
result = `rgb(${changeed.join(',')})`;
return { rgb: result, r: changeed[0], g: changeed[1], b: changeed[2] };
}
result = '无效';
return { rgb: result };
},
};
2. 颜色转换公式 <如背景红色,字体为白色,背景白色,字体为黑色>,自适应公式
const textColor = r * 0.299 + g * 0.587 + b * 0.114 > 186 ? '#000000' : '#FFFFFF';
3. 反差色计算<两种>
// 计算反色, ilighten - 减弱对比度(-1 ~ -15)
// 示例: oppositeColor("#000000", -4); 返回: #bbbbbb
function oppositeColor(a: string, ilighten: any) {
a = a.replace('#', '');
// var max16 = 15;
let max16 = Math.floor(15 + (ilighten || 0));
if (max16 < 0 || max16 > 15) max16 = 15;
let c16;
let c10;
const b = [];
for (let i = 0; i < a.length; i++) {
c16 = parseInt(a.charAt(i), 16); // to 16进制
c10 = parseInt(`${max16 - c16}`, 10); // 10进制计算
if (c10 < 0) c10 = Math.abs(c10);
b.push(c10.toString(16)); // to 16进制
console.log('十进制', c10, '16进制', b);
}
return `#${b.join('')}`;
}
/**
* 16进制色值获取反色设置方法
* @param {String} oldColor 为16进制色值的字符串(例:'#000000')
* @return {String} 返回反色的色值(例:'#ffffff')
*/
const colorReverse = (oldColor: any) => {
oldColor = `0x${`${oldColor}`.replace(/#/g, '')}`;
const str = `000000${(0xffffff - oldColor).toString(16)}`;
return `#${str.substring(str.length - 6, str.length)}`;
};