Skip to content

Instantly share code, notes, and snippets.

@alersenkevich
Last active March 2, 2020 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alersenkevich/329b38e0d8711b425265906439e6e996 to your computer and use it in GitHub Desktop.
Save alersenkevich/329b38e0d8711b425265906439e6e996 to your computer and use it in GitHub Desktop.
determine luminance by hex color
// 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