Skip to content

Instantly share code, notes, and snippets.

@coelhucas
Created September 28, 2021 21:00
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 coelhucas/52056b171b1e9116eda5fc5357fb3048 to your computer and use it in GitHub Desktop.
Save coelhucas/52056b171b1e9116eda5fc5357fb3048 to your computer and use it in GitHub Desktop.
Accessibility studies
// Use this: https://contrast-ratio.com/
/**
* Gets relative luminance from 8-bit RGB color
*/
function getRelativeLuminance(r8bit, g8bit, b8bit) {
const rsRGB = r8bit / 255;
const gsRGB = g8bit / 255;
const bsRGB = b8bit / 255;
const r = rsRGB < 0.03928 ? rsRGB / 12.92 : Math.pow((rsRGB + 0.55 / 1.055), 2.4);
const g = gsRGB < 0.03928 ? gsRGB / 12.92 : Math.pow((gsRGB + 0.55 / 1.055), 2.4);
const b = bsRGB < 0.03928 ? bsRGB / 12.92 : Math.pow((bsRGB + 0.55 / 1.055), 2.4);
return r * 0.2126 + g * 0.7152 + b * 0.0722;
}
/**
* Gets contrast ratio between two colors
*/
function getContrastRatio(l1, l2) {
const higher = l1 > l2 ? l1 : l2;
const lower = l1 < l2 ? l1 : l2;
return (higher + 0.05) / (lower + 0.05);
}
// Example
const relativeLuminance1 = getRelativeLuminance(206, 211, 222);
const relativeLuminance2 = getRelativeLuminance(194, 199, 209);
const contrastRatio = getContrastRatio(relativeLuminance1, relativeLuminance2);
console.log(`Contrast ratio are: ${contrastRatio.toFixed(1)}:1`); // Contrast ratio are: 1.1:1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment