Skip to content

Instantly share code, notes, and snippets.

@dannyid
Last active October 8, 2015 21:18
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 dannyid/2e6f919465e2424d4eb7 to your computer and use it in GitHub Desktop.
Save dannyid/2e6f919465e2424d4eb7 to your computer and use it in GitHub Desktop.
Find the best contrast color to overlay onto given color.
export function getContrastYIQ(color, colorType){
let r, g, b;
const start = color.indexOf('#') === 0 ? 1 : 0;
if (colorType === 'hex') {
r = parseInt(color.substr(start, 2), 16);
g = parseInt(color.substr(start + 2, 2), 16);
b = parseInt(color.substr(start + 4, 2), 16);
} else if (colorType == 'rgb') {
[r, g, b] = color.slice(4, -1).split(',').map(str => +str);
} else {
throw Error(`Incorrect color type given. Expected 'hex' or 'rgb', but saw '${colorType}'`);
}
const 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