colorsys
colorsys copied to clipboard
How to convert from RGB to HSV / HSL
Can this lib convert from RGB to HSL too?
by the way I saw this answer: https://stackoverflow.com/questions/8022885/rgb-to-hsv-color-in-javascript
I converted the function to TS and there is a bug:
export const rgb2hsv = (r: number, g: number, b: number) => {
let rr, gg, bb, h: number, s;
const rabs = r / 255;
const gabs = g / 255;
const babs = b / 255;
const v = Math.max(rabs, gabs, babs);
const diff = v - Math.min(rabs, gabs, babs);
const diffc= (c: number) => (v - c) / 6 / diff + 1 / 2;
const percentRoundFn = (num: number) => Math.round(num * 100) / 100;
if (diff == 0) {
h = s = 0;
} else {
s = diff / v;
rr = diffc(rabs);
gg = diffc(gabs);
bb = diffc(babs);
if (rabs === v) {
h = bb - gg;
} else if (gabs === v) {
h = (1 / 3) + rr - bb;
} else if (babs === v) {
h = (2 / 3) + gg - rr;
}
if (h < 0) { // bug: h is potentially undefined here
h += 1;
}else if (h > 1) {
h -= 1;
}
}
return {
h: Math.round(h * 360),
s: percentRoundFn(s * 100),
v: percentRoundFn(v * 100)
};
}
but my SO account is on the fritz and I cannot comment on his answer :(
h will always be defined because v will match one of the 3 conditions due to const v = Math.max(rabs, gabs, babs);. But I get that no linter will be able to understand that. :D