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

hsv2rgb is broken #20

Open
gapipro opened this issue Jul 22, 2014 · 2 comments
Open

hsv2rgb is broken #20

gapipro opened this issue Jul 22, 2014 · 2 comments

Comments

@gapipro
Copy link

gapipro commented Jul 22, 2014

Implementation of hsv2rgb function is incorrect.

If you convert color: #81c111 from hex to hsv and then back to hex you will get: #80c110

Problem is with decimal rounding.
Here is my fixed version:

    function hsv2rgb(hsv) {
        var R, G, B, X, C;
        var h = (hsv.h % 360) / 60;

        C = hsv.v * hsv.s;
        X = C * (1 - Math.abs(h % 2 - 1));
        R = G = B = hsv.v - C;

        h = ~~h;
        R += [C, X, 0, 0, X, C][h];
        G += [X, C, C, X, 0, 0][h];
        B += [0, 0, X, C, C, X][h];

        var r = Math.round(R * 255);
        var g = Math.round(G * 255);
        var b = Math.round(B * 255);
        return { r: r, g: g, b: b, hex: "#" + (16777216 | b | (g << 8) | (r << 16)).toString(16).slice(1), a:hsv.a };
    }
@DavidDurman
Copy link
Owner

Great. Could you please create a pull request?
I'm not sure about the simplification though. Compare:

If hsv.h is 350, then h = (350 % 360) / 60 = 5.833 and therefore (h % 2) = (5.833 % 2) = 1.833 but (1 - Math.abs(h % 2 - 1)) = (1 - Math.abs(5.833 % 2 - 1)) = 0.1669 which is not the same as 1.833.

@gapipro
Copy link
Author

gapipro commented Jul 22, 2014

Yes, I noticed that too. It would work if h was round number.

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