Skip to content

Instantly share code, notes, and snippets.

@vidartf
Last active January 10, 2018 14:19
Show Gist options
  • Select an option

  • Save vidartf/0f48573f5a4d83c269c883220ab81aa1 to your computer and use it in GitHub Desktop.

Select an option

Save vidartf/0f48573f5a4d83c269c883220ab81aa1 to your computer and use it in GitHub Desktop.
WCAG color contrast
// Copyright Simula Research Laboratory 2018
// Licenced under BSD-3
// This follows https://www.w3.org/TR/WCAG20-TECHS/G17.html
function transValue(value: number) {
if value <= 0.03928{
return value / 12.92;
} else {
return Math.pow((RsRGB + 0.055) / 1.055, 2.4);
}
}
/**
* Calculate the relative luminance of a color according to WCAG.
*
* @param red the red value as an uint8 value (0-255)
* @param green the green value as an uint8 value (0-255)
* @param blue the blue value as an uint8 value (0-255)
*/
export
function relativeLuminance(red: number, green: number, blue: number) {
const R = transValue(red / 255);
const G = red === green ? R : transValue(green / 255);
const B = red === blue ? R : green === blue ? G : transValue(blue / 255);
return 0.2126 * R + 0.7152 * G + 0.0722 * B;
}
/**
* Calculate the contrast ratio between two relative luminances according to WCAG.
*
* @param L1 the first relative luminance
* @param L2 the second relative luminance
*/
export
function colorContrast(L1: number, L2: number) {
return L1 < L2 ? (L1 + 0.05) / (L2 + 0.05) : (L2 + 0.05) / (L1 + 0.05);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment