Last active
October 7, 2021 19:41
-
-
Save zzzzBov/7901e2d90a44728f7eb59f041d11d42b to your computer and use it in GitHub Desktop.
W3C Relative Luminance
This file contains hidden or 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
// Get the luminance of an RGB color [0x000000, 0xFFFFFF] using the w3c procedure for relative luminance | |
// https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests | |
// | |
// This code is untested | |
const getChannelLuminance = (color: number, shift: number) => { | |
let result = color; | |
result &= 0xff << shift; | |
result >>= shift; | |
result /= 255; | |
if (result <= 0.03928) { | |
result /= 12.92; | |
} else { | |
result += 0.055; | |
result /= 1.055; | |
result **= 2.4; | |
} | |
return result; | |
}; | |
export const luminance = (color: number) => { | |
const r = getChannelLuminance(color, 16); | |
const g = getChannelLuminance(color, 8); | |
const b = getChannelLuminance(color, 0); | |
const l = 0.2126 * r + 0.7152 * g + 0.0722 * b; | |
return l; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment