Skip to content

Instantly share code, notes, and snippets.

@demidovsky
Created September 29, 2021 06:37
Show Gist options
  • Save demidovsky/3513205b2d465ccb9ba567bf37d36c4b to your computer and use it in GitHub Desktop.
Save demidovsky/3513205b2d465ccb9ba567bf37d36c4b to your computer and use it in GitHub Desktop.
RGB <-> HSV conversion
// input: h in [0,360] and s,v in [0,1]
// output: r,g,b in [0,1]
hsv2rgb(h,s,v) {
const f= (n,k=(n+h/60)%6) => v - v*s*Math.max( Math.min(k,4-k,1), 0);
return [f(5),f(3),f(1)];
}
// input: r,g,b in [0,1]
// output: h in [0,360) and s,v in [0,1]
rgb2hsv(r,g,b) {
let v=Math.max(r,g,b), c=v-Math.min(r,g,b);
let h= c && ((v==r) ? (g-b)/c : ((v==g) ? 2+(b-r)/c : 4+(r-g)/c));
return [60*(h<0?h+6:h), v&&c/v, v];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment