Wednesday, 15 October 2014

Calculating color contrast in JavaScript

image

To calculate which foreground color to use on a background we have the following function:

function getContrastYIQ(hexcolor){
var r = parseInt(hexcolor.substr(0,2),16);
var g = parseInt(hexcolor.substr(2,2),16);
var b = parseInt(hexcolor.substr(4,2),16);
var yiq = ((r*299)+(g*587)+(b*114))/1000;
return (yiq >= 128) ? 'black' : 'white';
}

Taken from: http://24ways.org/2010/calculating-color-contrast/

You can use this website to confirm it meets the W3C standards:  http://snook.ca/technical/colour_contrast/colour.html

No comments:

Post a Comment