Skip to content

Instantly share code, notes, and snippets.

@Alzy
Created March 28, 2019 02:22
Show Gist options
  • Select an option

  • Save Alzy/58b9172392bfd500cce7ff9fb416b5ff to your computer and use it in GitHub Desktop.

Select an option

Save Alzy/58b9172392bfd500cce7ff9fb416b5ff to your computer and use it in GitHub Desktop.
Given a hex color, return "black" or "white" depending on brightness. For use when you need to determine the right label color over a known color.
<!DOCTYPE html><html><head><title>COLOR COMPLIMENT</title></head><body><script type="text/javascript">
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 getColorBrightness(r, g, b){
return (r * 299 + g * 587 + b * 114) / 1000
}
function getBrightnessCompliment(hexColor) {
var rgbColor = hexToRgb(hexColor)
var brightnessValue = getColorBrightness(rgbColor.r, rgbColor.g, rgbColor.b)
return (brightnessValue > 150 ? 'black': 'white')
}
</script></body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment