Last active
October 8, 2015 21:18
-
-
Save dannyid/2e6f919465e2424d4eb7 to your computer and use it in GitHub Desktop.
Find the best contrast color to overlay onto given color.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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