Skip to content

Instantly share code, notes, and snippets.

@pangui
Last active January 18, 2017 00:23
Show Gist options
  • Save pangui/785bed6a82a24cc99ee29f886b3b1624 to your computer and use it in GitHub Desktop.
Save pangui/785bed6a82a24cc99ee29f886b3b1624 to your computer and use it in GitHub Desktop.
Obtain an RGB color based on wavelength
# credits: http://www.physics.sfasu.edu/astro/color/spectra.html
# Calculates an RGB color based on factor betwen 0 (380nm) and 1 (780nm)
def color_by_factor(f)
f = f.to_f
max = 255.0
wl = 380.0 + (780.0 - 380.0) * f
if wl >= 380 and wl <= 440
r = -1.0 * (wl - 440.0)/(440.0 - 380.0)
g = 0.0
b = 1.0
elsif wl > 440 and wl <= 490
r = 0.0
g = (wl - 440.0)/(490.0 - 440.0)
b = 1.0
elsif wl > 490 and wl <= 510
r = 0.0
g = 1.0
b = -1.0 * (wl - 510.0)/(510.0 - 490.0)
elsif wl > 510 and wl <= 580
r = (wl - 510.0)/(580.0 - 510.0)
g = 1.0
b = 0.0
elsif wl > 580 and wl <= 645
r = 1.0
g = -1.0 * (wl - 645.0)/(645.0 - 580.0)
b = 0.0
elsif wl > 645 and wl <= 780
r = 1.0
g = 0.0
b = 0.0
end
if wl > 700
sss = 0.3 + 0.7 * (780.0 - wl)/(780.0 - 700.0)
elsif wl < 420
sss = 0.3 + 0.7 * (wl - 380.0)/(420.0 - 380.0)
else
sss = 1.0
end
'#' + [r, g, b].map{|c| (max * c * sss) }.map(&:to_i).map{|c| c.to_s(16).upcase.rjust(2, '0') }.join
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment