DavidDurman / FlexiColorPicker

A pure JavaScript color picker - no images, external libraries, CSS or 1px divs.
http://www.daviddurman.com/flexi-color-picker/
414 stars 149 forks source link

hsv2rgb is broken #20

Open gapipro opened 10 years ago

gapipro commented 10 years ago

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 commented 10 years ago

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 commented 10 years ago

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