2017-04-04 71 views
2

我得到的body的颜色和背景颜色的计算HEX像这样走:挑选颜色更是从白色

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); 

我需要选择其中一种颜色用作文本颜色在白色背景上。但是,页面背景较暗并且颜色较浅/白色时会出现问题。因此,我需要智能地选择其中的一个用作文本颜色。

我如何知道colorbg中的哪一个离#fff最远?

+0

最远在什么意义?你想选择最对比的颜色? – byxor

+0

这完全正确。这两种颜色中的哪一种在视觉上最适合作为文本'color'使用,当'background:#fff;' –

+0

将使用CSS颠倒属性(https://davidwalsh.name/invert-colors-css)做什么你要?它你想要一个JavaScript函数,这是一个搞清楚如何在JavaScript中进行反转的问题。像这样:http://stackoverflow.com/questions/6961725/algorithm-for-calculating-inverse-color – zelite

回答

1

您需要计算两种颜色的relative luminance。较低亮度的颜色将是离白色更远的颜色。公式为这种计算在链接的文章,并在下面我的代码提供:

{ 
 
    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; 
 
}