Reputation: 17869
I have a function that will convert a hex code into rgb for me:
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;
}
I would like to have a second function that will also take a hex code, but then modify it such that it is the equivalent gray of what the -webit-filter: grayscale(100%)
would do.
the function would look like this:
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;
}
I am not sure on what determines the equivalent gray based on a color, and my research did not help much either. Any ideas?
Upvotes: 0
Views: 713
Reputation: 59363
Use the grayscale formula, like this:
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
This is the formula:
Y' = 0.2126R + 0.7152G + 0.0722B
Upvotes: 2