Skip to content

Instantly share code, notes, and snippets.

@andrewgleave
Last active August 29, 2015 14:03
Show Gist options
  • Save andrewgleave/d0e5ae1ac85abd11eb22 to your computer and use it in GitHub Desktop.
Save andrewgleave/d0e5ae1ac85abd11eb22 to your computer and use it in GitHub Desktop.
Determine best contrast color (black/white) for a given color
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
function contrastColor(color) {
var rgb = hexToRgb(color);
var r = rgb.r * 255,
g = rgb.g * 255,
b = rgb.b * 255;
var yiq = (r * 299 + g * 587 + b * 114) / 1000;
return (yiq >= 128) ? '#111' : '#fff';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment