Last active
August 29, 2015 14:17
-
-
Save Higgs1/16c8447fcbcf39d6f7df to your computer and use it in GitHub Desktop.
Javascript 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, val]. All 6 values are between 0...1. | |
function rgb2hsv(r, g, b) { | |
var v = Math.max(r, g, b), | |
x = v - Math.min(r, g, b); | |
return [ | |
( x == 0 ? 0 : | |
v == g ? (b - r) / x + 2 : | |
v == b ? (r - g) / x + 4 : | |
(g - b) / x + 6 | |
) % 6 / 6, | |
v == 0 ? 0 : x / v, | |
v | |
] | |
} | |
// Returns [red, green, blue]. All 6 values are between 0...1. | |
function hsv2rgb(h, s, v) { | |
var c = v * s, | |
h = h * 6, | |
x = c * (1 - Math.abs(h % 2 - 1)), | |
m = v - c, | |
[r, g, b] = | |
h < 1 ? [c, x, 0] : | |
h < 2 ? [x, c, 0] : | |
h < 3 ? [0, c, x] : | |
h < 4 ? [0, x, c] : | |
h < 5 ? [x, 0, c] : | |
[c, 0, x]; | |
return [r + m, g + m, b + m] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment