Skip to content

Instantly share code, notes, and snippets.

@andresgcarmona
Forked from lerouxb/contrast.coffee
Created July 25, 2020 19:34
Show Gist options
  • Save andresgcarmona/abd877739abd7c041de97d1dd7da92ca to your computer and use it in GitHub Desktop.
Save andresgcarmona/abd877739abd7c041de97d1dd7da92ca to your computer and use it in GitHub Desktop.
The W3C's suggested color contrast algorithm
# http://www.w3.org/TR/AERT#color-contrast
getBrightness = (rgb) ->
sum = parseInt(rgb[0])*299 + parseInt(rgb[1])*587 + parseInt(rgb[2])*114
brightness = Math.round(sum / 1000) # 0 (dark) to 255 (light)
colorDifference = (a, b) ->
max = Math.max
min = Math.min
d0 = max(a[0], b[0]) - min(a[0], b[0])
d1 = max(a[1], b[1]) - min(a[1], b[1])
d2 = max(a[2], b[2]) - min(a[2], b[2])
d0+d1+d2
colorContrast = (a, b) ->
b0 = getBrightness(a)
b1 = getBrightness(b)
contrast =
brightness: Math.abs(b0-b1)
difference: colorDifference(a, b)
contrast
hasEnoughContrast = (a, b) ->
contrast = colorContrast(a, b)
contrast.brightness > 125 and contrast.difference > 500
##
one = [0, 0, 0]
two = [255, 255, 255]
console.log hasEnoughContrast(one, two)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment