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/16c8447fcbcf39d6f7df to your computer and use it in GitHub Desktop.
Save Higgs1/16c8447fcbcf39d6f7df to your computer and use it in GitHub Desktop.
Javascript RGB ⇔ HSV
// 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