·  阅读 10482

# 思考

### 突发奇想

`0.213``0.715``0.072`三个数字是如何来的，感兴趣的同学可以去了解一下Color FAQ颜色矩阵

# 开始实践

``````const rgbArr = [15, 35, 64];

``````/**
* 转换字体颜色
*
* @param {array} rgbArr rgb数组
*/
function resBgColor(rgbArr) {
// 当color值大于128时,color值偏向255,即#ffffff,此时字体颜色应为#000000
// 当color值小于128时,color值偏向0,即#000000,此时字体颜色应为#ffffff
var color = 0.213 * rgbArr[0] + 0.715 * rgbArr[1] + 0.072 * rgbArr[2] > 255 / 2;
return color? '#000000': '#ffffff'
}

## 使用

``````var textColor = resBgColor(rgbArr);
console.log(textColor)      // #ffffff

## 进阶

``````rgbArr = [15, 35, 64];

``````function findTextColor(colorValue) {
// #123456或者rgb(12,34,56)转为rgb数组[12,34,56]
const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})\$/;
var that = colorValue;
if (/^(rgb|RGB)/.test(that)) {
// 处理rgb转为数组
var aColor = that.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
return resBgColor(aColor);
} else if (reg.test(that)) {
// 处理十六进制色值
var sColor = colorValue.toLowerCase();
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return resBgColor(sColorChange);
} else {
return false;
}
} else {
return false;
}
}

## 再次使用

``````// 用法一:
var textColor = findTextColor('#000');
console.log(textColor);     // #ffffff

// 用法二:
var textColor2 = findTextColor('rgb(255, 255, 255)');
console.log(textColor2);    // #000000

## 更酷炫的玩法

JavaScript：

``````var textDom = document.getElementById('color-text');
var obj = document.getElementById("picker");

var a = Colorpicker.create({
el: "color-picker",
color: "#0081ff",
change: function (elem, hex) {
textDom.style.color = TEXTColor.colorRgb(hex);
elem.style.backgroundColor = hex;
}
})

HTML：

``````<div class="container">
<h2>点击下方选择颜色</h2>
<div class="picker" id="color-picker">
<div id="color-text">文字颜色</div>
</div>
</div>

# 为你所用

## 安装方法

``````npm install textcolor --save

``````<script type="type/javascript" src="https://unpkg.com/textcolor@1.0.2/textcolor.js" ></script>

## 用法

``````import TEXTColor from 'textcolor'

let hex = '#000000';        // or '#666' or 'rgb(12,34,56)'
let textcolor = TEXTColor.findTextColor(hex);
console.log(textcolor)      // #ffffff