james kampel
james kampel

Reputation: 55

Converting HSV to RGB is not working Javascript

I am trying to convert HSV to RGB with Javascript.

For some reason, the output is not correct. The numbers returned are crazy. For instance, when passing in hsv(0, 100, 100) to the function, it returns rgb(25500, -2524500, -2524500);

That is obviously not a valid RGB value.

Here is the function that converts HSV to RGB :

function HSVtoRGB(h, s, v) {
    var r, g, b, i, f, p, q, t;
    if (arguments.length === 1) {
        s = h.s, v = h.v, h = h.h;
    }
    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q = v * (1 - f * s);
    t = v * (1 - (1 - f) * s);
    switch (i % 6) {
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }
    return {
        r: Math.round(r * 255),
        g: Math.round(g * 255),
        b: Math.round(b * 255)
    };
}

Upvotes: 2

Views: 1469

Answers (1)

james kampel
james kampel

Reputation: 55

Turns out, the function works properly.
The issue was with the values I was passing in.

Instead of hsv(50, 100, 100), use hsv(50/360, 1, 1).

You must divide the hue by 360, and the S and V are up to 1, not 100.

Upvotes: 3

Related Questions