问题描述
我试图评估一个颜色选择器选择的颜色的黑暗,看看它是否太黑,如果是,设置为白色。我想我可以使用十六进制值的第一个字符拉这个。
我有这样的代码:
if(lightcolor.substring(0,3)==#00|| lightcolor.substring(0,3)==#010){
lightcolor = #FFFFFF;
color = lightcolor;
}
必须有一个更有效的方法与十六进制数学知道一种颜色超出了一定的黑暗程度?像lightcolor +某些十六进制值< =某些十六进制值,然后将其设置为白色。
我添加了tinyColor,这可能对此有用,但我不确定。
A bunch!
您必须单独提取三个RGB组件,然后使用标准公式将结果
<$ c
假设一个六字符的颜色: c> 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; //根据ITU-R BT.709
if(luma //选择不同的颜色
}
EDIT
自2014年5月 tinycolor
现在有一个 getBrightness()
函数,尽管使用CCIR601加权因子而不是上述ITU-R。 b $ b
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.
I have code doing this:
if (lightcolor.substring(0,3) == "#00"|| lightcolor.substring(0,3) == "#010"){
lightcolor="#FFFFFF";
color=lightcolor;
}
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.
I have tinyColor added, which might be of use for this, but I don't know for sure.
A bunch!
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
}
EDIT
Since May 2014 tinycolor
now has a getBrightness()
function, albeit using the CCIR601 weighting factors instead of the ITU-R ones above.
这篇关于如何检查十六进制颜色是否为“太黑”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!