/**
* @description 根据背景色计算文字颜色
* @param {string} backgroundHexColor 传入 #FFFBBC | FBC | FFBBCC 均可
*/
static recommendFontColor(backgroundHexColor) {
let hex = backgroundHexColor
if (hex.startsWith('rgb')) {
hex = this.convertRGBToHex(hex);
}
// 如果当前传入的参数以 # 开头,去除当前的
if (hex.startsWith('#')) {
hex = hex.substring(1);
}
// 如果当前传入的是 3 位小数值,直接转换为 6 位进行处理
if (hex.length === 3) {
hex = [hex[0], hex[0], hex[1], hex[1], hex[2], hex[2]].join('')
}
if (hex.length !== 6) {
throw new Error('Invalid background color.' + backgroundHexColor);
}
const r = parseInt(hex.slice(0, 2), 16)
const g = parseInt(hex.slice(2, 4), 16)
const b = parseInt(hex.slice(4, 6), 16)
if ([r, g, b].some(x => Number.isNaN(x))) {
throw new Error('Invalid background color.' + backgroundHexColor);
}
const textColor = (r * 0.299 + g * 0.587 + b * 0.114) > 186 ? '#000' : '#FFF'
return textColor
}
/**
* @description 传入rgb,返回16进制
* @param {string} rgb rgb数值
*/
convertRGBToHex(rgb) {
/** 获取背景色中的多个值,即 rgb(2,2,2) => [2,2,2] */
const rgbRegex = /^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/
/** 转换 10 进制为 16 进制,
* 计算完成后时字符串前面加 0,同时取后两位数值。使得返回的数值一定是 两位数
* 如 E => 0E | FF => 0FF => FF
*/
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2);
const bg = rgb.match(rgbRegex);
if (!bg) {
// 返回空字符串,在后面判断长度为 6 时候会报错。不在此处进行操作
return ''
}
return ("#" + hex(bg[1]) + hex(bg[2]) + hex(bg[3])).toUpperCase();
}