我想展示一些像这个例子的图片

填充颜色由数据库中颜色为十六进制的字段决定(例如:ClassX -> color: #66FFFF)。 现在,我想显示上面的数据与所选的颜色填充(如上图),但我需要知道如果颜色是暗或光,所以我知道如果文字应该在白色或黑色。 有办法吗?谢谢大家


当前回答

我正在使用tinyColor库,它也可以做这项工作。

import { TinyColor } from '@ctrl/tinycolor'

// ...

getColorContrast(color = '#66FFFF'): string {
  if(new TinyColor(color).getLuminance() > 0.179) { // 0.179 -> Mark Ransom answer
     return '#000'
  } else {
     return '#fff'
  }
}

此方法也接受rgb颜色,如rgb(102,255,255)

其他回答

我使用这个JavaScript函数将rgb/rgba转换为“白色”或“黑色”。

function getTextColor(rgba) {
    rgba = rgba.match(/\d+/g);
    if ((rgba[0] * 0.299) + (rgba[1] * 0.587) + (rgba[2] * 0.114) > 186) {
        return 'black';
    } else {
        return 'white';
    }
}

你可以输入这些格式中的任何一种它会输出"黑"或"白"

rgb (255,255,255) rgba (255,255,255,0.1) 色彩:rgba (255,255,255,0.1) 255,255,255,0.1

这只是一个示例,它将在单击元素时更改SVG复选标记的颜色。它将根据所单击元素的背景色将复选标记颜色设置为黑色或白色。

checkmarkColor: function(el) {
    var self = el;
    var contrast = function checkContrast(rgb) {
        // @TODO check for HEX value

        // Get RGB value between parenthesis, and remove any whitespace
        rgb = rgb.split(/\(([^)]+)\)/)[1].replace(/ /g, '');

        // map RGB values to variables
        var r = parseInt(rgb.split(',')[0], 10),
            g = parseInt(rgb.split(',')[1], 10),
            b = parseInt(rgb.split(',')[2], 10),
            a;

        // if RGBA, map alpha to variable (not currently in use)
        if (rgb.split(',')[3] !== null) {
            a = parseInt(rgb.split(',')[3], 10);
        }

        // calculate contrast of color (standard grayscale algorithmic formula)
        var contrast = (Math.round(r * 299) + Math.round(g * 587) + Math.round(b * 114)) / 1000;

        return (contrast >= 128) ? 'black' : 'white';
    };

    $('#steps .step.color .color-item .icon-ui-checkmark-shadow svg').css({
        'fill': contrast($(self).css('background-color'))
    });
}

onClickExtColor: function(evt) {
    var self = this;

    self.checkmarkColor(evt.currentTarget);
}

https://gist.github.com/dcondrey/183971f17808e9277572

我正在使用tinyColor库,它也可以做这项工作。

import { TinyColor } from '@ctrl/tinycolor'

// ...

getColorContrast(color = '#66FFFF'): string {
  if(new TinyColor(color).getLuminance() > 0.179) { // 0.179 -> Mark Ransom answer
     return '#000'
  } else {
     return '#fff'
  }
}

此方法也接受rgb颜色,如rgb(102,255,255)

以我对类似问题的回答为基础。

您需要将十六进制代码分解为3个部分,以获得单独的红色、绿色和蓝色强度。代码的每两个数字代表一个十六进制(以16为基数)表示法的值。这里我就不详细讲了,它们很容易查到。

一旦有了各个颜色的强度,就可以确定颜色的整体强度并选择相应的文本。

if (red*0.299 + green*0.587 + blue*0.114) > 186 use #000000 else use #ffffff

186的阈值是基于理论的,但可以根据口味进行调整。根据评论,低于150的阈值可能更适合您。


Edit: The above is simple and works reasonably well, and seems to have good acceptance here at StackOverflow. However, one of the comments below shows it can lead to non-compliance with W3C guidelines in some circumstances. Herewith I derive a modified form that always chooses the highest contrast based on the guidelines. If you don't need to conform to W3C rules then I'd stick with the simpler formula above. For an interesting look into the problems with this see Contrast Ratio Math and Related Visual Issues.

The formula given for contrast in the W3C Recommendations (WCAG 2.0) is (L1 + 0.05) / (L2 + 0.05), where L1 is the luminance of the lightest color and L2 is the luminance of the darkest on a scale of 0.0-1.0. The luminance of black is 0.0 and white is 1.0, so substituting those values lets you determine the one with the highest contrast. If the contrast for black is greater than the contrast for white, use black, otherwise use white. Given the luminance of the color you're testing as L the test becomes:

if (L + 0.05) / (0.0 + 0.05) > (1.0 + 0.05) / (L + 0.05) use #000000 else use #ffffff

这在代数上简化为:

if L > sqrt(1.05 * 0.05) - 0.05

或约:

if L > 0.179 use #000000 else use #ffffff

唯一剩下的就是计算l。该公式也在指南中给出,它看起来像从sRGB到线性RGB的转换,然后是ITU-R建议BT.709的亮度。

for each c in r,g,b:
    c = c / 255.0
    if c <= 0.04045 then c = c/12.92 else c = ((c+0.055)/1.055) ^ 2.4
L = 0.2126 * r + 0.7152 * g + 0.0722 * b

阈值0.179不应该改变,因为它与W3C指南相关联。如果你发现结果不是你喜欢的,试试上面更简单的公式。

LESS有一个很好的对比度()函数,对我来说效果很好,请参阅http://lesscss.org/functions/#color-operations-contrast

“在两种颜色中选择一种颜色与另一种颜色形成最大的对比。 这对于确保颜色在背景下是可读的很有用,这对于可访问性遵从也很有用。此函数的工作方式与Compass for SASS中的对比函数相同。根据WCAG 2.0,颜色是用伽马校正的亮度值来比较的,而不是它们的亮度。”

例子:

p {
    a: contrast(#bbbbbb);
    b: contrast(#222222, #101010);
    c: contrast(#222222, #101010, #dddddd);
    d: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 30%);
    e: contrast(hsl(90, 100%, 50%), #000000, #ffffff, 80%);
}

输出:

p {
    a: #000000 // black
    b: #ffffff // white
    c: #dddddd
    d: #000000 // black
    e: #ffffff // white
}