Last active
March 2, 2020 12:17
-
-
Save alersenkevich/329b38e0d8711b425265906439e6e996 to your computer and use it in GitHub Desktop.
determine luminance by hex color
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
// HEX to RGB function | |
const hexToRgb = hex => | |
hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (m, r, g, b) => `#${r + r + g + g + b + b}`) | |
.substring(1) | |
.match(/.{2}/g) | |
.map(x => parseInt(x, 16)) | |
// Determine relation of luminance in color | |
const luminance = (r, g, b) => { | |
const a = [r, g, b].map((v) => { | |
v /= 255 | |
return v <= 0.03928 | |
? v / 12.92 | |
: ((v + 0.055) / 1.055) ** 2 | |
}) | |
return (a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722) | |
} | |
// Using | |
const backgroundColor = '#0366d6' | |
const rgb = hexToRgb(backgroundColor) // make rgb from hex, got array of r, g, b | |
// push the array by spread operator to function | |
// if spread doesn't work or not awailable, use luminance(rgb[0], rgb[1], rgb[2]) | |
const lum = luminance(...rgb) | |
const textColor = (lum < 0.228) ? '#FFFFFF' : '#000000' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment