Last active
August 29, 2015 14:17
-
-
Save Higgs1/f2a53a5e77a902d1e00e to your computer and use it in GitHub Desktop.
CoffeeScript RGB ⇔ HSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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