Skip to content

Instantly share code, notes, and snippets.

@lekevicius
Created February 23, 2013 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lekevicius/5020342 to your computer and use it in GitHub Desktop.
Save lekevicius/5020342 to your computer and use it in GitHub Desktop.
HSL and HSV conversion to RGB in CoffeeScript
hue2rgb = (p, q, t) ->
t += 1 if t < 0
t -= 1 if t > 1
return p + (q - p) * 6 * t if t < 1/6
return q if t < 1/2
return p + (q - p) * (2/3 - t) * 6 if t < 2/3
return p
hslToRgb = (h, s, l) ->
if s is 0
r = g = b = l # achromatic
else
if l < 0.5
q = l * (1 + s)
else
q = l + s - l * s
p = 2 * l - q
r = hue2rgb p, q, h + 1/3
g = hue2rgb p, q, h
b = hue2rgb p, q, h - 1/3
[ Math.round(r * 255), Math.round(g * 255), Math.round(b * 255) ]
hsvToRgb = (h, s, v) ->
i = Math.floor(h * 6)
f = h * 6 - i
p = v * (1 - s)
q = v * (1 - f * s)
t = v * (1 - (1 - f) * s)
switch i % 6
when 0 then [r, g, b] = [v, t, p]
when 1 then [r, g, b] = [q, v, p]
when 2 then [r, g, b] = [p, v, t]
when 3 then [r, g, b] = [p, q, v]
when 4 then [r, g, b] = [t, p, v]
when 5 then [r, g, b] = [v, p, q]
[ Math.round(r * 255), Math.round(g * 255), Math.round(b * 255) ]
rgbToHex = (rgb) ->
'#' + rgb[0].toString(16) + rgb[1].toString(16) + rgb[2].toString(16)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment