Skip to content

Instantly share code, notes, and snippets.

@Stichoza
Last active October 16, 2018 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stichoza/d0c2135d30ee7ea63c6b7c47e51c66cf to your computer and use it in GitHub Desktop.
Save Stichoza/d0c2135d30ee7ea63c6b7c47e51c66cf to your computer and use it in GitHub Desktop.

Two colors provide good color visibility if the brightness difference and the color difference between the two colors are greater than a set range.

Color brightness is determined by the following formula: ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000 Note: This algorithm is taken from a formula for converting RGB values to YIQ values. This brightness value gives a perceived brightness for a color.

Color difference is determined by the following formula: (maximum (Red value 1, Red value 2) - minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) - minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) - minimum (Blue value 1, Blue value 2))

The rage for color brightness difference is 125. The range for color difference is 500.

http://www.w3.org/WAI/ER/WD-AERT/#color-contrast

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';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment