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

The toHex function may produce an incorrect hexadecimal value when it encounters a negative color component. #25

Open
rhinoc opened this issue Dec 14, 2024 · 0 comments

Comments

@rhinoc
Copy link

rhinoc commented Dec 14, 2024

In certain scenarios, the color components may be negative, leading to the generation of an invalid hex value.

  // transform hex to oklch
  const hex = "#a96800";
  const color = fromHex(new Array(3), hex); // [0.6627450980392157, 0.40784313725490196, 0]
  const oklch = toOklch(color) as [number, number, number]; // [0.575356813769678, 0.12642355966665692, 0.188380147597491]

  // reverse transform oklch to hex, in this case the color2[2] is already **negative**
  const color2 = fromOklch(new Array(3), ...oklch); // [0.6627451073936355, 0.4078431276995599, -3.3454380928166215e-7]
  // because toHex use Math.round, so it may still gets correct hex
  const hex2 = toHex(color2); // ✅ "#A96800"

  // but in some bad case, for example, when precision lost in further processing, the hex value may be wrong
  const oklchRounded = [0.58, 0.13, 0.19] as const;
  const color3 = fromOklch(new Array(3), ...oklchRounded); // [0.671842467563041, 0.41184974144751946, -0.041825356581836816];
  const hex3 = toHex(color3); // ❌ "#B"
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

1 participant