Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to convert from RGB to HSV / HSL #29

Open
ORESoftware opened this issue Dec 29, 2020 · 1 comment
Open

How to convert from RGB to HSV / HSL #29

ORESoftware opened this issue Dec 29, 2020 · 1 comment

Comments

@ORESoftware
Copy link

ORESoftware commented Dec 29, 2020

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

@gr8bit
Copy link

gr8bit commented Dec 8, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants