Skip to content

Instantly share code, notes, and snippets.

@ArtOfCode-
Created September 13, 2018 20:10
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 ArtOfCode-/f01c2fb1249f810621de7a0cefd561f7 to your computer and use it in GitHub Desktop.
Save ArtOfCode-/f01c2fb1249f810621de7a0cefd561f7 to your computer and use it in GitHub Desktop.
WCAG 2.0 contrast ratio implementation in JavaScript/ES6
/**
* Get the contrast ratio between two colors specified in RGB, as defined by WCAG 2.0.
* Ex:
*
* getContrastRatio([0, 0, 0], [255, 255, 255]); // => 21 (white vs black, i.e. full contrast)
* getContrastRatio([0, 0, 0], [255, 0, 0]); // => 5.252 (red vs black)
*
* References/resources:
* https://www.w3.org/TR/WCAG20/#contrast-ratiodef
* https://www.w3.org/TR/WCAG20/#relativeluminancedef
* https://colorable.jxnblk.com
* https://webaim.org/resources/contrastchecker/
*/
const getContrastRatio = (() => {
const srgbFrom8Bit = val => val / 255;
const getLuminanceComponent = srgb => srgb <= 0.03928 ? srgb / 12.92 : Math.pow((srgb + 0.055) / 1.055, 2.4);
const getRelativeLuminance = (r, g, b) => 0.2126 * getLuminanceComponent(srgbFrom8Bit(r)) +
0.7152 * getLuminanceComponent(srgbFrom8Bit(g)) +
0.0722 * getLuminanceComponent(srgbFrom8Bit(b));
const darkerOf = (c1, c2) => c1.reduce((a, e) => a + e) >= c2.reduce((a, e) => a + e) ? c2 : c1;
const lighterOf = (c1, c2) => c1.reduce((a, e) => a + e) >= c2.reduce((a, e) => a + e) ? c1 : c2;
return (c1, c2) => (getRelativeLuminance(...lighterOf(c1, c2)) + 0.05) /
(getRelativeLuminance(...darkerOf(c1, c2)) + 0.05);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment