javascript找到正确的灰色为黑白效果

时间:2013-08-04 02:58:00

标签: javascript colors rgb

我有一个函数可以将十六进制代码转换为rgb给我:

function getRGB(color){    
    var matchColors = /#(\w{2})(\w{2})(\w{2})/;
    var match = matchColors.exec(color);
    var r = parseInt(match[1], 16).toString() + ",";
    var g = parseInt(match[2], 16).toString() + ",";
    var b = parseInt(match[3], 16).toString();
    answer = 'rgb(' + r + g + b + ')' ;
    return answer;
}

我想有一个第二个函数,它也会采用十六进制代码,但是然后修改它,使它与-webit-filter: grayscale(100%)的等效灰色相同。

函数看起来像这样:

function gray(color){   
    var matchColors = /#(\w{2})(\w{2})(\w{2})/;
    var match = matchColors.exec(color);
    var r = parseInt(match[1], 16).toString() + ",";
    var g = parseInt(match[2], 16).toString() + ",";
    var b = parseInt(match[3], 16).toString();
    //code to modify figure out the rgb gray value and assign it to the variable G
    answer = 'rgb(' + G + ',' + G + ',' + G + ')' ;
    return answer;
}

我不确定基于颜色的等效灰色是什么,我的研究也没有多大帮助。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

使用the grayscale formula,如下所示:

var r = parseInt(match[1], 16),
    g = parseInt(match[1], 16),
    b = parseInt(match[1], 16),
    val = Math.floor(0.2126 * r + 0.7152 * g + 0.0722 * b)
    answer = 'rgb(' + val + ','  + val + ',' + val + ')'

return answer

这是公式:

Y' =  0.2126R + 0.7152G + 0.0722B

Updated fiddle