5
头图

Overview

In the front-end field, we often need to deal with colors. Except for some front-ends that have been transferred from design (ps: historical reasons), most of the new generation of front-ends are basically born in science and engineering, and generally have not undergone special design. Training and training, so that in the process of restoring the design drawings, the understanding of color will be more or less different, which will lead to unnecessary contradictions between the design and the front end (ps: this is the same root, and mutual understanding), the purpose of this article is By introducing some relevant color knowledge, I will provide you with some views from the dual perspectives of design and front-end, and I hope to provide you with some different knowledge and understanding of color.

color theory

In fact, human research on color has been recorded for a long time, but to really take color as a discipline or have its theoretical system, we have to start with Newton. In the process of continuous scientific development, people gradually have different colors. It is precisely because of the development of science that color theory has made great progress in different fields. This article focuses on sharing two color theories that we need to understand for our front-end, namely: color wheel theory and addition and subtraction color mode theory.

color ring

The color wheel theory has gone through several different stages, such as the Newton color wheel, the Eaton color wheel (traditional color wheel), the Munsell color wheel, and the Yurmby color wheel. As an important theoretical course in the Bauhaus system, it has a huge impact on the design field (ps: For children's shoes interested in design history, please refer to the previous article on the history of modern world design ), in general, the color wheel theory can be simple The following common color concepts are extracted:

name Degree of difference explain
adjacent color 0-15 degrees The difference between the two colors in the color wheel is small and relatively close, and the recognition degree of different people is different, usually the recognition degree is low
similar color 15-45 degrees The difference between the two colors in the color wheel is moderate, which has both recognition and similarity
Medium color difference 45-105 degrees The difference between the two colors in the color wheel has obvious recognition, but it will not appear too jumpy
Contrasting colors 105-150 degrees The difference between the two colors in the color wheel has a strong recognition degree, which is easy to produce a sense of jump.
adjacent complementary colors 150-179 degrees There is a big difference between the two colors in the color wheel, so it is not recommended to use them together
Complementary colors 180 degree The two colors in the color wheel have a strong contrast

Additive Color Mode & Subtractive Color Mode

Before introducing the additive color mode and the subtractive color mode, let's first look at some basic knowledge about color that we have learned since elementary school. When we were in school before, art teachers may have taught the concept of three primary colors and three primary colors, or differentiated optical three primary colors and color three primary colors, etc. This is actually a preliminary understanding of additive color mode and subtractive color mode. In essence: The three primary colors or the three primary colors are just a basic color proposed based on materials in different environments. Here I distinguish between the optical three primary colors and the color three primary colors. The optical three primary colors are: red (R), green (G), blue (B) , is also the primary color commonly used in our front-end development process; in addition to the optical three primary colors, there is also a color three primary colors, or three art primary colors, which are: red (M), yellow (Y), blue (C), this is Primary colors often used in printing or painting. I believe that careful classmates have found that when I am marking English, the red and blue of the three primary colors of color and the three primary colors of optics seem to be different. Yes, it is precisely because of the different use of colors in different scenes, and the color is added. Different patterns emerged in the process of integration. Here, we will introduce the core theory of our part, namely: additive color mode and subtractive color mode.

The definitions of the imprecise additive color mode and subtractive color mode are given below

Additive mode refers to the mode that adds the attributes in the color model; subtractive mode refers to the mode that absorbs the attributes in the color model

So why is optical color additive and artistic color subtractive? Because in essence, in optical scenes, such as computer monitors, it is usually used to emit different primary colors from a light source to present colors to people, and different display manufacturing materials have different display characteristics, such as: cathode ray tube Displays (CRTs), Plasma Displays (PDPs), Liquid Crystal Displays (LCDs), and Organic Light Emitting Semiconductor Displays (OLEDs), etc., but these are usually emitted from a light source, so these are usually additive color models, and generally speaking There will be RGB model, YUV (YCrCb) model, etc. In the front-end, we often use the RGB model to perform the relevant corresponding code operations, which involves the color model, please see the introduction in the next part. In art or printing scenes, it is the principle of using objects to reflect light, which means that the color of objects we see every day is actually the color that it cannot be absorbed. For example, pink pigment actually absorbs all colors except pink. So we can see that it is pink, so subtractive color is actually a mode of absorption, so in the CMYK model, it is a typical subtractive color mode.

color model

After having a preliminary understanding of color, if we want to describe color, we need to establish a model to describe it. Here we introduce the concept of color model . Based on Wikipedia and Baidu Encyclopedia, we give the following loosely Definition:

A color model describes a subset of visible light with a tuple or set, where the tuple is usually a ternary or a quaternary.

Generally speaking, according to whether the device is related, we can divide the color model into device-related color model and device-independent color model. Based on this, it can be roughly divided into two systems, namely: RGB system and XYZ system, here we will introduce The following common color models are: RGB/CMYK, YUV/YCrCb, HS*, Lab, XYZ. The relevant color models will be introduced below.

RGB & CMYK

The RGB model is a typical additive model, which combines different models of multiple colors by establishing RGB as the three primary colors, where R/G/B are respectively represented as dimensions in the three -dimensional Euclidean space , and the colors are related to the construction, as above as shown in the figure.

Different from the additive synthesis of the RGB model, for printing-related scenes, it is a typical subtractive synthesis, and the most common here is the material-related basic pigment as the dimension of the basic model space, the most common is the CMYK model , which is still It is a model construction that conforms to the Euclidean space, except that subtractive synthesis is used in the algorithm process of synthesis.

YUV & YCrCb

As a variant of the RGB model, the YUV model is often used for color representation in video and television fields. Since in the field of video and television, the indicators of hue and saturation are relatively more critical, so U+V is used to represent chroma, and Y is used to represent brightness.

With the development of video coding technology, the YCbCr model is used as a deformation model standard for video streams. It no longer expresses chrominance through u+v, but through the difference between R and luminance of the RGB input signal, namely Cr and through The difference between B and brightness of the RGB input signal, that is, Cb, is dimensionally constructed, which is a digital color-difference signal rather than an analog color signal compared to YUV or YPrPb encoding.

YUV and YCrCb color models are often used in computer vision related analysis. Students who are related to video and image analysis can learn more about them.

HSV & HSL & HSB & HSI

For human vision, it is usually easiest to describe the distinction based on Hue, Saturation, and the last brightness or brightness, but for the last two indicators, the construction of different models is actually are not the same, here we will focus on two models, namely: HSL-like and HSV-like models

For the HSL model , the last defined index is a quantity mixed with black and white, and its final form is a full cone in Euclidean space, as shown in the figure above.

For the HSV model , the last defined indicator is just a black quantity mixed in, and its final form is an inverted cone in Euclidean space, as shown in the figure above.

It is precisely because of this difference in the treatment of S and * that there are many different nouns and representation models. Here we use the following table to compare the common HS* model:

shorthand full name Notes
HSV Hue, Saturation, Value lightness
HSL Hue, Saturation, Lightness brightness
HSB Hue, Saturation, Brightness lightness
HSI Hue, Saturation, Intensity brightness
Conclusion: HSV = HSB, HSL ≈ HSI

As shown in the figure above, if we do not give special instructions in the future, we will use HSV and HSL as the two typical representatives of HS*. As a variant of the RGB model, we will follow up in the HS* calculation process. HS* The conversion with RGB model will be explained in detail.

LAB

With the development, people's research on color is no longer limited to the limitation of the basic conditions of the equipment. Therefore, the CIE (Commission Internationale de Photométrie) International Illumination Association proposed the Lab model , which is different from the RGB model, where L represents brightness, and a is the transition from dark green (low light) to gray (medium light) to bright pink (high light), b is bright blue (low light) to gray (medium light) to yellow (high light) ) transition, and its synthetic model is shown in the figure above.

XYZ

In the previous Lab model, we know that CIE has conducted further research on color. In fact, the Lab model is also a derivative variant of the XYZ model . It distinguishes the light sources in the RGB model in terms of coordinate systems. A related correction is made, which is device-independent, as shown above, in Euclidean space, the two coordinate systems are offset. (ps: For specific changes, you can refer to this article for RGB color system and XYZ color system )

color space

The color space is also known as the color gamut. In the previous part, we introduced different color models. Then, various actual situations will be encountered in the actual production process. Therefore, each manufacturer or organization will be based on their own equipment or scenes. The formed color mapping relationship, thus proposing their respective color ranges, here we combine wiki encyclopedia and Baidu encyclopedia, and give the following definitions loosely:

A color space is a mapping relationship based on a color model to the color range of a specific scene.

For common color spaces, we list the following:

color space color model Notes
sRGB RGB model A general color standard developed by Microsoft in conjunction with HP, Mitsubishi and other manufacturers. The general color standard has a small color range and is also a commonly used color space standard in web pages.
Adobe RGB RGB model Adobe leads the development and uses computer equipment to simulate the color style of printed products as much as possible
ProPhoto RGB RGB model A color space standard developed by Kodak, commonly used in high-end cameras
Japan Color 2001 Coated CMYK model A color space standard developed by the Japan Printing Industry Association
SWOP CMYK CMYK model US Web Coated, a color space standard developed by the US printing industry
CIE 1931 XYZ XYZ model CIE standard established in 1931
CIELAB Lab model Compliant with CIE 1931 standard, improved from CIE LUV

color system

After talking about some basic theories and descriptions of color, let's take a look at the related application and practice of color in the design field, which will also be a good prelude to the collaboration between our front-end and design students.

If it is formulated according to the standards of the design system, it usually needs to include the three layers of 愿景与原则(Vision & Principle) , 指南(Guidelines) , 库与工具(Libraries & Tools) , among which:

The first layer: Vision & Principle, is the core value and overall program of the design system, guiding the style and tone of the overall design system.

The second layer: Guidelines (Guidelines), including Style Guideline, Patterns Guideline, Content Guideline and more content conveyed through text and images, is also the most important design for color ( Color), Layout, .

The third layer: Libraries & Tools, including components library (Components Libraries), toolkits (Toolkits), collaborative tools (Collaborative Tools) and other content that can be used directly, generally output component libraries that can be developed , Use sketch or psd design resources and figma, axure and other materials used in the product. (ps: Large-scale design teams will also collaborate with the front-end to make corresponding component libraries. For example, common antd and element component libraries are the front-end resources of the corresponding design team. Generally speaking, large-scale teams may divide design and front-end into users. Experience team, of course, this also depends on the overall organizational structure)

When I was designing before, I had done related design systems. Interested students can read this corresponding design system practice - 2018 Summary - UI Basic Framework Specification for Multiple Business Lines Parallel (with case)

After the introduction of the design system just now, we saw that in the guidelines of the second layer, a very important part of the specification for the style part is color. In fact, color is the most important tool for designers in the visual process. In the House system, color composition , which is one of the three major components, is an important design theory. If color is constructed into a commercial system, it usually needs to include two parts, namely: general color system and commercial color system. .

For the classification of color systems, here I will use the ant design color system of Ant Financial as a template to describe.

The universal color system, which is the system-level color system mentioned in antd, does not contain any specific color requirements for business and products, but the designer selects several specific colors to express different colors with different visual feelings. communication needs.

The commercial color system, that is, the product-level color system mentioned in antd, usually needs to be selected and set from the above-mentioned general color system in conjunction with brand tonality, product functions, etc., so as to better serve the commercialization, In the words of Mr. Wang Shouzhi: "Design is external, and art is internal."

At this stage, the integration of design and engineering is also getting closer and closer, and the design system and engineering system can be connected by means such as Design Token , so as to resolve the communication cost problem in the process of design and front-end link, and improve engineering efficiency. Regarding the improvement of design links, you can see several introductions on design engineering by Ant Financial in last year's SEE Conf-- Exploration and Application of Design Tokens, an Artifact of Efficiency Improvement - Yuxing & Yuanyao , Design Engineering Three Song - Yu Yu & Wen Bing

Here I list the color system styles made by several well-known design teams. You can refer to them:

design team color system Remark
Ant Design Ant Design Color System
Element Design Element Design color system
Material Design Material Design color system
Human Interface Guidelines Apple Color System
Fluent Design Microsoft Color System

Color calculation

After a rational understanding of color theory, color model, color space, and a perceptual experience of the color system, in the last part, let’s look at how the previously established rationality and perceptualness are integrated through calculation. In this part, I will focus on introducing and Our front-end related color model conversion (RGB and HSV/HSL), as well as a brief introduction to the mathematical calculation method (Bézier curve) that may be involved in the conversion process, and finally we will take a look at the implementation of ant design's color palette specific application of color.

RGB/HSL/HSV conversion

After having the previous understanding of the color model, let's take a look at how the color models are converted. Since the front-end application process mainly involves the conversion of RGB to HS*, here we only introduce how the RGB model is converted to HSL. And HSV for coordinate system conversion.

From the video we can see that the process of RGB -> HSV is:

RGB tilt => pull into a hexagonal pyramid => turn into a hexagonal prism => turn into a cylinder

And the process of RGB -> HSL is:

RGB tilt => pull into double hexagonal pyramid => turn into hexagonal prism => turn into cylinder

From this process, we can get the following conversion formula after a series of complex mathematical conversions:

Note: R, G, B are all values converted to the 0-1 interval, that is, the R/G/B here is the original 0-255 The value of the interval is divided by 255 to get the corresponding value

Hue conversion

The calculation of H is the same for the three, namely:

Conversion of Lightness/Value/Intensity

From the above conversion process, we can see that the corresponding equations of L, V, and I are:

Conversion of Saturation

For the conversion of saturation, due to the differences in L, V, and I, S in the conversion process has also changed:

Bezier curve

As an important method in numerical calculation, Bezier curve plays a very important role in dynamically fitting different motion trajectories. As an important method for processing Bernstein polynomials in interpolation calculation, it is very important for scientific computing.

In the process of color calculation, using the Bezier curve to process two data values is also a very important means, which can be closer to the construction of the color system and the fitting of the real color world.

Ant Design Swatches

After introducing all color-related models, calculations, etc., let's take a look at some applications of color calculation in the front end. Here we take the generation algorithm of Ant Design 's color palette of Ant Financial as an example to conduct some simple analysis. Let's take a look at the specific implementation of color calculation in the component library. For a more detailed introduction, you can take a look at this "Ant Design Swatch Generation Algorithm Evolution" written by the right-hand man. Here I just do it. A brief description of personal understanding and analysis.

antd swatch 1.x algorithm

 // 变亮
@function tint($color, $percentage) {
    @return mix(white, $color, $percentage);
}
// 变暗
@function shade($color, $percentage) {
    @return mix(black, $color, $percentage);
}
// 使用
.useage {
    background-color: tint(#2db7f5, 80%);
}

The method of the first version is very simple. We see that the mixture of black and white is directly used for processing. The mix here is the color mixing method in sass. Here, a simple RGB model is used for conversion. The specific conversion method I found dart- The method in sass :

 /// Returns [color1] and [color2], mixed together and weighted by [weight].
SassColor _mixColors(SassColor color1, SassColor color2, SassNumber weight) {
  // This algorithm factors in both the user-provided weight (w) and the
  // difference between the alpha values of the two colors (a) to decide how
  // to perform the weighted average of the two RGB values.
  //
  // It works by first normalizing both parameters to be within [-1, 1], where
  // 1 indicates "only use color1", -1 indicates "only use color2", and all
  // values in between indicated a proportionately weighted average.
  //
  // Once we have the normalized variables w and a, we apply the formula
  // (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1. This
  // formula has two especially nice properties:
  //
  //   * When either w or a are -1 or 1, the combined weight is also that
  //     number (cases where w * a == -1 are undefined, and handled as a
  //     special case).
  //
  //   * When a is 0, the combined weight is w, and vice versa.
  //
  // Finally, the weight of color1 is renormalized to be within [0, 1] and the
  // weight of color2 is given by 1 minus the weight of color1.
  var weightScale = weight.valueInRange(0, 100, "weight") / 100;
  var normalizedWeight = weightScale * 2 - 1;
  var alphaDistance = color1.alpha - color2.alpha;

  var combinedWeight1 = normalizedWeight * alphaDistance == -1
      ? normalizedWeight
      : (normalizedWeight + alphaDistance) /
          (1 + normalizedWeight * alphaDistance);
  var weight1 = (combinedWeight1 + 1) / 2;
  var weight2 = 1 - weight1;

  return SassColor.rgb(
      fuzzyRound(color1.red * weight1 + color2.red * weight2),
      fuzzyRound(color1.green * weight1 + color2.green * weight2),
      fuzzyRound(color1.blue * weight1 + color2.blue * weight2),
      color1.alpha * weightScale + color2.alpha * (1 - weightScale));
}

It can be seen that the linear calculation of the RGB model is used here. Due to the huge change in the interval during the linear conversion of the RGB model, it is very unfriendly to the visual effect of the human eye.

antd swatch 2.x algorithm

 @import "bezierEasing";
@import "tinyColor";

// We create a very complex algorithm which take the place of original tint/shade color system
// to make sure no one can understand it 👻
// and create an entire color palette magicly by inputing just a single primary color.
// We are using bezier-curve easing function and some color manipulations like tint/shade/darken/spin
.colorPaletteMixin() {
@functions: ~`(function() {
  var warmDark = 0.5;     // warm color darken radio
  var warmRotate = -26;  // warm color rotate degree
  var coldDark = 0.55;     // cold color darken radio
  var coldRotate = 10;   // cold color rotate degree
  var getShadeColor = function(c) {
    var shadeColor = tinycolor(c);
    // warm and cold color will darken in different radio, and rotate in different degree
    // warmer color
    if (shadeColor.toRgb().r > shadeColor.toRgb().b) {
      return shadeColor.darken(shadeColor.toHsl().l * warmDark * 100).spin(warmRotate).toHexString();
    }
    // colder color
    return shadeColor.darken(shadeColor.toHsl().l * coldDark * 100).spin(coldRotate).toHexString();
  }
  var primaryEasing = colorEasing(0.6);
  this.colorPalette = function(color, index) {
    var currentEasing = colorEasing(index * 0.1);
    // return light colors after tint
    if (index <= 6) {
      return tinycolor.mix(
        '#ffffff',
        color,
        currentEasing * 100 / primaryEasing
      ).toHexString();
    }
    return tinycolor.mix(
      getShadeColor(color),
      color,
      (1 - (currentEasing - primaryEasing) / (1 - primaryEasing)) * 100
    ).toHexString();
  };
})()`;
}
// It is hacky way to make this function will be compiled preferentially by less
// resolve error: `ReferenceError: colorPalette is not defined`
// https://github.com/ant-design/ant-motion/issues/44
.colorPaletteMixin();

In the second version of the algorithm, the overall swatch granularity was changed using the HSL model and then converted to the RGB model.

Among them, when dividing the granularity based on the HSL model, the author here uses a transformation method defined by himself. For the judgment of gray level, the comparison between r and b is used, and the rotation angle and darken ratio here are personally thought by the author. The experience value obtained from the actual production data, here I have not obtained the corresponding pushing basis from the relevant data.

The mixing of RGB here no longer uses the method in sass, but is based on the mixing method in tinyColor. The mix method is as follows:

 tinycolor.mix = function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
};

The proportion in the mixing process is no longer linear, but a curve drawn by a fixed Bezier curve. It can be seen from the above figure that it is basically a linear fit.

antd swatch 3.x algorithm

The pre-algorithm, to judge the brightness, uses the algorithm formula of converting to grayscale (ps: 601 correction formula, derived from the NTSC brightness equation), namely:

Y = 0.299 R + 0.587 G + 0.114 * B

In the tinycolor library, the implementation is as follows:

 function getBrightness() {
    //http://www.w3.org/TR/AERT#color-contrast
    var rgb = this.toRgb();
    return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
},

The following isLight is obtained from the above getBrightness

 /* stylelint-disable no-duplicate-selectors */
@import "bezierEasing";
@import "tinyColor";

// We create a very complex algorithm which take the place of original tint/shade color system
// to make sure no one can understand it 👻
// and create an entire color palette magicly by inputing just a single primary color.
// We are using bezier-curve easing function and some color manipulations like tint/shade/darken/spin
.colorPaletteMixin() {
@functions: ~`(function() {
  var hueStep = 2;
  var saturationStep = 0.16;
  var saturationStep2 = 0.05;
  var brightnessStep1 = 0.05;
  var brightnessStep2 = 0.15;
  var lightColorCount = 5;
  var darkColorCount = 4;

  var getHue = function(hsv, i, isLight) {
    var hue;
    if (hsv.h >= 60 && hsv.h <= 240) {
      hue = isLight ? hsv.h - hueStep * i : hsv.h + hueStep * i;
    } else {
      hue = isLight ? hsv.h + hueStep * i : hsv.h - hueStep * i;
    }
    if (hue < 0) {
      hue += 360;
    } else if (hue >= 360) {
      hue -= 360;
    }
    return Math.round(hue);
  };
  var getSaturation = function(hsv, i, isLight) {
    var saturation;
    if (isLight) {
      saturation = hsv.s - saturationStep * i;
    } else if (i === darkColorCount) {
      saturation = hsv.s + saturationStep;
    } else {
      saturation = hsv.s + saturationStep2 * i;
    }
    if (saturation > 1) {
      saturation = 1;
    }
    if (isLight && i === lightColorCount && saturation > 0.1) {
      saturation = 0.1;
    }
    if (saturation < 0.06) {
      saturation = 0.06;
    }
    return Number(saturation.toFixed(2));
  };
  var getValue = function(hsv, i, isLight) {
    var value;
    if (isLight) {
      value = hsv.v + brightnessStep1 * i;
    }else{
      value = hsv.v - brightnessStep2 * i
    }
    if (value > 1) {
      value = 1;
    }
    return Number(value.toFixed(2))
  };

  this.colorPalette = function(color, index) {
    var isLight = index <= 6;
    var hsv = tinycolor(color).toHsv();
    var i = isLight ? lightColorCount + 1 - index : index - lightColorCount - 1;
    return tinycolor({
      h: getHue(hsv, i, isLight),
      s: getSaturation(hsv, i, isLight),
      v: getValue(hsv, i, isLight),
    }).toHexString();
  };
})()`;
}
// It is hacky way to make this function will be compiled preferentially by less
// resolve error: `ReferenceError: colorPalette is not defined`
// https://github.com/ant-design/ant-motion/issues/44
.colorPaletteMixin();

For the current antd swatch generation algorithm, here is the relevant fusion based on the HSV model, where:

  1. For Hue, the granularity of Hue is segmented from 60 to 240 degrees;
  2. For saturation, the deepening and dodging parts are processed with different granularities, and the dodging is faster;
  3. For lightness, the reduction of lightness is also larger than the summation granularity;

Different from the Bezier curve used in 2.x to fit the curve, here it is changed back to linear combination to make controllable adjustments in line with the color system, so that the overall scheme is particularly clear, but different from the one in 1.x Violent combination, the grayscale calculation here is a conversion based on the brightness equation as a scientific basis, which is a combination of the characteristics of 1.x and 2.x

Summarize

In the process of front-end development, when we help designers to construct the color system, in addition to the understanding of some common perception levels in daily life, we should pay more attention to the exploration and exploration of the deep principles, and ask the deep scientific cognition, for Our exploration of the depth of the front-end field plays a crucial role, such as the exploration of computer vision in color, which allows us to provide a higher-level and dimensional understanding of the extension of the engineering and design link. In the process, they can get a cognitive exploration of their own work boundaries by exploring the underlying questions.

Color research is not only related to color theory, color model, color space, color calculation, etc. In fact, color is a very interesting and in-depth subject, and it is even more important for our front-end, as a connection between design and data. As the link between users and enterprises, we also supplement the relevant scientific theoretical knowledge while learning the front-end theory, so as to be able to use the knowledge flexibly and help enterprises and users to improve a better experience. Our higher value as front-end engineers lies in our mutual encouragement! ! !

refer to


维李设论
1.1k 声望4k 粉丝

专注大前端领域发展