However, a bit of digging around on Google, and I found a much simpler answer. You could take the three RGB values, average them, and set each of the values to that average. But that’s not particularly accurate.
Why not? Our eyes have differing levels of sensitivity when it comes to red, green and blue. If you calculate a weighted average based on this differing sensitivity, then you get a better greyscale representation of that colour.
The co-efficients of red, green and blue on the second line represent the sensitivity of our eyes to those colours. The value of
k represents how much the colour should be desaturated, where
1 means fully desaturated.
There are a few more bits we need to cover so that we can make use of this function easily. Namely, fetching the RGB values for an element, and setting them again.
Getting it is easy, as jQuery returns us a string of the RGB values which we can parse using regular expressions. Setting it is easy too - we just need to turn the array returned by
desaturate into a valid CSS string.
Here are the functions that do just that, assuming you’ve got jQuery loaded: