The effect

Take a look at the renderings first

demand

We have a requirement that users can customize the theme color. But when I used the color picker to choose different colors, I found a problem. If the user chooses black as the theme color and the font color is also black, he will not see the font.

thinking

A whim

When thinking about how to determine the background color and when to use black or white font, there is a method in Photoshop to remove color to remind me.

Color removal: the RGB three channel color information set to the same; That is: R=G=B, then the image becomes gray, and in order to keep the brightness of the image unchanged, the sum of R, G and B in the same channel should be 1. Namely: R + G + B = 1; For example: 0.213+0.715+0.072 = 1; RGB=0.213, 0.715, 0.072;

(0.213,0.715,0.072How did the three numbers come from, interested students can go to understandColor FAQandColor matrix)

Why does it have to be grey?

Color is divided into two categories: color system and color system, color system and color system.

The biggest difference depends on, have color department to have color 3 attribute and hue, saturation, lightness.

No color system will not be interfered by hue, saturation. (Black, white and grey belong to colorless system)

referenceGrayscale and Color

What’s the point of doing that?

We can compare the color value of the background color with the color value of the normal gray.

If the background color is larger than the normal gray color, it indicates that the background color is black. Use white font.

If the background color is less than the normal gray color, it indicates that the background color is white. In this case, use black font.

Began to practice

So let’s see if we can do that

Let’s select an RGB color value and change it to an array:

const rgbArr = [15, 35, 64];
Copy the code

Since the color value of gray is (128, 128, 128), the relative size of RGB can be identified by judging the gray color value 255/2

** @param {array} rgbArr RGB array */functionResBgColor (rgbArr) {// When the color value is greater than 128, the color value is biased to 255, i.e# FFFFFF, in which case the font color should be #000000// When the color value is less than 128, the color value is biased to 0, i.e#000000, the font color should be # FFFFFFVar color = 0.213 * rgbArr[0] + 0.715 * rgbArr[1] + 0.072 * rgbArr[2] > 255/2;return color? '# 000000': '#ffffff'
}
Copy the code

use

var textColor = resBgColor(rgbArr);
console.log(textColor)      // #ffffff
Copy the code

It worked. It was so easy to do. So how to make the above GIF effect to achieve?

The advanced

We usually use RGB (12,34,56) or #123456 for color configuration. In order to use resBgcolor, we need to compile a new function to convert findTextColor to an array of rgbArr

rgbArr = [15, 35, 64];
Copy the code

The following method is the final code that returns the RGB array uniformly and executes the font match resBgcolor(colorValue)

function findTextColor(colorValue) {
    // Convert #123456 or RGB (12,34,56) to RGB array [12,34,56]
    const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    var that = colorValue;
    if(/ ^ (RGB | RGB) /. The test (that)) {/ / processing RGB converted to an array of var aColor. = that replace (/ (? :\(|\)|rgb|RGB)*/g,"").split(",");
        return resBgColor(aColor);
    } else if(reg.test(that)) {// Handle hexadecimal color values 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; }}Copy the code

Again using

Var textColor = findTextColor();'# 000');
console.log(textColor);     // #ffffffVar textColor2 = findTextColor('rgb(255, 255, 255)');
console.log(textColor2);    // # 000000
Copy the code

More cool gameplay

I introduce a color selector into the HTML page and assign the color of my text to the value returned by the selector.

Here is the main code

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; }})Copy the code

HTML:

<div class="container"> <h2> Click below to select the color </h2> <div class="picker" id="color-picker">
        <div id="color-text"> Text color </div> </div>Copy the code

Specific demo has been uploaded to Github, you can also download my demo to play on Github (⭐).

For you

I have wrapped and published this function on NPM, which you can install via NPM install or reference directly

Installation method

Method 1: Introduce through NPM

npm install textcolor --save
Copy the code

Method two: import through

<script type="type/javascript" src="https://unpkg.com/[email protected]/textcolor.js" ></script>
Copy the code

usage

How to use TEXTColor

import TEXTColor from 'textcolor'

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

conclusion

If this article has helped you in any way, thank you for giving the author a thumbs up at 😄