如何检查十六进制颜色是否“太黑"? [英] How to check if hex color is "too black"?
问题描述
我正在尝试评估颜色选择器选择的颜色的暗度,看它是否太黑",如果是,则将其设置为白色.我想我可以使用十六进制值的第一个字符来解决这个问题.它正在工作,但它也在切换一些合法的浅色"颜色.
I'm trying to evaluate the darkness of a color chosen by a color picker to see if it's "too black", and if so, set it to white. I thought I could use the first characters of the hex value to pull this off. It's working, but it's switching some legitimately "light" colors too.
我有这样做的代码:
if (lightcolor.substring(0,3) == "#00"|| lightcolor.substring(0,3) == "#010"){
lightcolor="#FFFFFF";
color=lightcolor;
}
必须有一种更有效的十六进制数学方法来知道颜色已经超出了一定程度的暗度?就像如果 lightcolor + "some hex value" <= "some hex value" 然后将其设置为白色.
There must be a more efficient way with hex math to know that a color has gone beyond a certain level of darkness? Like if lightcolor + "some hex value" <= "some hex value" then set it to white.
我添加了 tinyColor,这可能对此有用,但我不确定.
I have tinyColor added, which might be of use for this, but I don't know for sure.
推荐答案
您必须分别提取三个 RGB 分量,然后使用标准公式将生成的 RGB 值转换为它们的感知亮度.
You have to extract the three RGB components individually, and then use a standard formula to convert the resulting RGB values into their perceived brightness.
假设有六个字符的颜色:
Assuming a six character colour:
var c = c.substring(1); // strip #
var rgb = parseInt(c, 16); // convert rrggbb to decimal
var r = (rgb >> 16) & 0xff; // extract red
var g = (rgb >> 8) & 0xff; // extract green
var b = (rgb >> 0) & 0xff; // extract blue
var luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709
if (luma < 40) {
// pick a different colour
}
编辑
自 2014 年 5 月起,tinycolor
现在具有 getBrightness()
函数,尽管使用的是 CCIR601 加权因子而不是上面的 ITU-R 加权因子.
Since May 2014 tinycolor
now has a getBrightness()
function, albeit using the CCIR601 weighting factors instead of the ITU-R ones above.
编辑
产生的亮度值范围是 0..255,其中 0 是最暗的,255 是最亮的.tinycolor
将大于 128 的值视为浅色.(无耻地从@pau.moreno 和@Alnitak 的评论中复制)
The resulting luma value range is 0..255, where 0 is the darkest and 255 is the lightest. Values greater than 128 are considered light by tinycolor
. (shamelessly copied from the comments by @pau.moreno and @Alnitak)
这篇关于如何检查十六进制颜色是否“太黑"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!