Converts Hue/Saturation/Lightness values to 8bit RGB values - Node.js CSS

Node.js examples for CSS:Color

Description

Converts Hue/Saturation/Lightness values to 8bit RGB values

Demo Code

    /*from w w w. j a v a 2 s  .c om*/
/*  viscommon.js
    
    This file serves as a place to store code currently common or that may be useful to
    other visualization features.
    
    Created by cadorett 2/18/2012
    
*/


/**
 * Gets the RGB colors of the given session and field.
 * 
 * @param fIndex The index of the field to color.
 * @param sIndex The index of the session to color.
 * 
 * @return Returns a list of the three RGB values.
 */
function getFieldColor(fIndex, sIndex) {
    var shade = parseInt(getFieldShade(fIndex).slice(0, 2), 16);
    
    return hslToRgb(( 0.6 + ( 1.0 * sIndex / data.sessions.length )) % 1.0, 1.0, .2 + shade / 255);
}

/**
 * Gets the color value for the given session index.
 * 
 * @param index The index of the session.
 * 
 * @return Returns the session color.
 */
function getSessionColor(index) {
    return hslToRgb((0.6 + (1.0 * index / data.sessions.length)) % 1.0, 0.825, 0.425);
}



/*
    hslToRGB convers Hue/Saturation/Lightness values
    to 8bit RGB values. This is for generating unique
    colors for sessions/fields. I copy/pasted this from
    the interwebs because I'm a classy programmer.
    
                        - Eric F.
*/ 
function hslToRgb(h, s, l){
    var r, g, b;

    if(s == 0){
        r = g = b = l; // achromatic
    }else{
        function hue2rgb(p, q, t){
            if(t < 0) t += 1;
            if(t > 1) t -= 1;
            if(t < 1/6) return p + (q - p) * 6 * t;
            if(t < 1/2) return q;
            if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        }

        var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        var p = 2 * l - q;
        r = Math.floor( hue2rgb(p, q, h + 1/3) * 255 );
        g = Math.floor( hue2rgb(p, q, h) * 255 );
        b = Math.floor( hue2rgb(p, q, h - 1/3) * 255 );
    }

    return [r, g, b];
}

/*
    TODO: Validate this comment
    
    Assuming this function simply converts from rgb color representation
    to hex representation.
*/
function rgbToHex(hex){
    return toHex(hex[0])+toHex(hex[1])+toHex(hex[2]);
}

/*
    TODO: Validate this comment
    
    Assuming this function simply converts from decimal color representation
    to hexadecimal representation
*/
function toHex(n){
    n = parseInt(n, 10);
    if( isNaN(n) ) return '00';
    n = Math.max(0, Math.min(n, 255));
    return '0123456789ABCDEF'.charAt( (n-n%16) / 16 ) + '0123456789ABCDEF'.charAt(n%16);
}

Related Tutorials