colorsys icon indicating copy to clipboard operation
colorsys copied to clipboard

How to convert from RGB to HSV / HSL

Open ORESoftware opened this issue 4 years ago • 1 comments

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 :(

ORESoftware avatar Dec 29 '20 23:12 ORESoftware

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

gr8bit avatar Dec 08 '23 16:12 gr8bit