Pick color that's further away from white
I'm getting the computed HEX of the color and background color of body
like so:
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[s+]?([s+]?(d+)[s+]?,[s+]?(d+)[s+]?,[s+]?(d+)[s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
var color = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).color);
var bg = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).backgroundColor);
I need to pick one of these colors to be used as a text color on a white background. However, a problem occurs when the page background is dark and the color is light/white. Therefore, I need to intelligently pick one of these to be used as the text color.
How can I find out which one of color
and bg
is furthest away from #fff
?
You need to calculate relative luminance of both colors. Color with the lower luminance, will be the one further from white. Formula for this calculation is provided in the linked article and in my code below:
{
const getRGBLuminance = (string) => {
const rgb = string.replace(/[^d ]/g, '').split(' ');
return 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2];
}
const bodyStyle = window.getComputedStyle(document.body),
colorLuminance = getRGBLuminance(bodyStyle.color),
bgColorLuminance = getRGBLuminance(bodyStyle.backgroundColor);
if (colorLuminance < bgColorLuminance) {
console.log('Text color is further from #FFF.');
}
else if (colorLuminance > bgColorLuminance) {
console.log('Background color is further from #FFF.');
}
else {
console.log('Both color and background color are equally far from #FFF.');
}
}
/* Only for demonstration */
body {
background-color: #ACE;
color: #000;
}
链接地址: http://www.djcxy.com/p/87064.html
上一篇: 将RGB转换为RGBA白色
下一篇: 选择离白色更远的颜色