Skip to content

Instantly share code, notes, and snippets.

@archonic
Created September 13, 2018 20:26
Show Gist options
  • Save archonic/ae6054fe1870623b9b1f44e19613dc59 to your computer and use it in GitHub Desktop.
Save archonic/ae6054fe1870623b9b1f44e19613dc59 to your computer and use it in GitHub Desktop.
Ruby font colour based on background colour. Outputs white or black based on hex luminance.
def text_colour(bg_colour)
rgb = [bg_colour[0..1], bg_colour[2..3], bg_colour[4..5]].map! do |c|
c = c.to_i(16).to_f / 255.0
c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055)**2.4
end
(0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) <= 0.5 ? "fff" : "000"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment