Skip to content

Instantly share code, notes, and snippets.

@Higgs1
Last active August 29, 2015 14:17
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 Higgs1/f2a53a5e77a902d1e00e to your computer and use it in GitHub Desktop.
Save Higgs1/f2a53a5e77a902d1e00e to your computer and use it in GitHub Desktop.
CoffeeScript RGB ⇔ HSV
# Returns [hue, sat, value] when given red, green, blue. All 6 values are between 0...1.
rgb2hsv = (r, g, b) ->
v = Math.max r, g, b
x = v - Math.min r, g, b
[
( if x is 0
0
else if v is r
(g - b) / x
else if v is g
(b - r) / x + 2
else
(r - g) / x + 4
) %% 6 / 6
if v is 0
0
else
x / v
v
]
# Returns [red, green, blue] when given hue, sat, value. All 6 values are between 0...1.
hsv2rgb = (h, s, v) ->
c = v * s
h = h * 6
x = c * (1 - Math.abs h % 2 - 1)
[r, g, b] =
if h < 1
[c, x, 0]
else if h < 2
[x, c, 0]
else if h < 3
[0, c, z]
else if h < 4
[0, x, c]
else if h < 5
[x, 0, c]
else
[c, 0, x]
m = v - c
[r + m, g + m, b + m]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment