Skip to content

Instantly share code, notes, and snippets.

@Accudio
Created June 9, 2022 08:54
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 Accudio/b9cb16e0e3df858cef0d31e38f1fe46f to your computer and use it in GitHub Desktop.
Save Accudio/b9cb16e0e3df858cef0d31e38f1fe46f to your computer and use it in GitHub Desktop.
Basic JavaScript implementation of a WCAG 2.1 colour contrast algorithm that chooses between black or white depending on the colour provided
console.log(contrastingColour('#eee'))
function contrastingColour(colour) {
const rgb = hexToRGB(colour)
// luminance of inputted colour
const L = 0.2126 * colourMod(rgb.r) + 0.7152 * colourMod(rgb.g) + 0.0722 * colourMod(rgb.b)
// white has a luminance of 1
const whiteL = 1
// contrast calculation
const contrast = (whiteL + 0.05) / (L + 0.05)
// return white or black depending on the contrast calculation
return contrast > 4.5 ? '#fff' : '#000'
}
// convert '#678ab4' to [r, g, b] format
function hexToRGB(hex) {
// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
hex = hex.replace(shorthandRegex, function(m, r, g, b) {
return r + r + g + g + b + b;
});
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16)
} : null;
}
// convert colour in range 0-255 to the modifier used within luminance calculation
function colourMod(colour) {
const sRGB = colour / 255
let mod = Math.pow((sRGB + 0.055) / 1.055, 2.4)
if (sRGB < 0.03928) mod = sRGB / 12.92
return mod
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment