#788 ✓ invalid
Guy Mann

HSV to RGB function

Reported by Guy Mann | July 12th, 2010 @ 11:39 PM

RFC

I wanted a native function for converting from HSV values to RGB for my colors. I added the following code. The original code was found by me at http://snipplr.com/view/14590/hsv-to-rgb/. The comments have been left in for consistency I have been using it without issue in 2 applications for some time.

/* HSV to RGB color conversion H runs from 0 to 360 degrees S and V run from 0 to 100 Ported from the excellent java algorithm by Eugene Vishnevsky at: http://www.cs.rit.edu/~ncs/color/t_convert.html */ p.hsvToRgb = function hsvToRgb(h, s, v) {

var r, g, b;
var i;
var f, p, q, t;

// Make sure our arguments stay in-range
h = Math.max(0, Math.min(360, h));
s = Math.max(0, Math.min(100, s));
v = Math.max(0, Math.min(100, v));

// We accept saturation and value arguments from 0 to 100 because that's
// how Photoshop represents those values. Internally, however, the
// saturation and value are calculated from a range of 0 to 1. We make
// That conversion here.
s /= 100;
v /= 100;

if(s == 0) {
    // Achromatic (grey)
    r = g = b = v;
    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

h /= 60; // sector 0 to 5
i = Math.floor(h);
f = h - i; // factorial part of h
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));

switch(i) {
    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;

    default: // case 5:
        r = v;
        g = p;
        b = q;
}

return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];

}

Comments and changes to this ticket

Please Sign in or create a free account to add a new ticket.

With your very own profile, you can contribute to projects, track your activity, watch tickets, receive and update tickets through your email and much more.

New-ticket Create new ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

Processing.js is an open programming language for people who want to program images, animation, and interactions for the web without using Flash or Java applets. Processing.js uses Javascript to draw shapes and manipulate images on the HTML5 Canvas element. The code is light-weight, simple to learn and makes an ideal tool for visualizing data, creating user-interfaces and developing web-based games.

Shared Ticket Bins

People watching this ticket

Pages