Last active
February 17, 2022 12:35
-
-
Save lerouxb/10969295 to your computer and use it in GitHub Desktop.
The W3C's suggested color contrast algorithm
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
# 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
My function and variable naming is a bit all over the place..