Created
February 22, 2023 10:20
-
-
Save stekhn/249bd921b08f2b7609bcd7d2c4942d3e to your computer and use it in GitHub Desktop.
Get the contrast ratio of two hex colors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const hex2Rgb = (hexString) => { | |
const groups = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hexString); | |
return groups | |
? [ | |
parseInt(result[1], 16), | |
parseInt(result[2], 16), | |
parseInt(result[3], 16), | |
] | |
: null; | |
}; | |
const getLuminanace = (hexString) => { | |
const rgbValues = hex2rgb(hexString); | |
const lightnessMap = rgbValues.map((v) => { | |
const lightness = v / 255; | |
return lightness <= 0.03928 | |
? lightness / 12.92 | |
: ((lightness + 0.055) / 1.055) ** 2.4; | |
}); | |
return Number( | |
( | |
0.2126 * lightnessMap[0] + | |
0.7152 * lightnessMap[1] + | |
0.0722 * lightnessMap[2] | |
).toFixed(3) | |
); | |
}; | |
const getContrastRatio = (colorA, colorB) => { | |
const luminanceA = getLuminanace(colorA); | |
const luminanceB = getLuminanace(colorB); | |
return ( | |
(Math.max(luminanceA, luminanceB) + 0.05) / | |
(Math.min(luminanceA, luminanceB) + 0.05) | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment