Last active
August 29, 2015 14:03
-
-
Save andrewgleave/d0e5ae1ac85abd11eb22 to your computer and use it in GitHub Desktop.
Determine best contrast color (black/white) for a 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
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