Skip to content

Instantly share code, notes, and snippets.

@zzzzBov
Last active October 7, 2021 19:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zzzzBov/7901e2d90a44728f7eb59f041d11d42b to your computer and use it in GitHub Desktop.
Save zzzzBov/7901e2d90a44728f7eb59f041d11d42b to your computer and use it in GitHub Desktop.
W3C Relative Luminance
// 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