Color Extravaganza

HSL Color Conversions (RGB and Hex) with tests!

by ChaseMoskal

HTML

<h1>HSL Color Conversion Tests</h1>
<pre><output id="out"></output></pre>

CSS

html { font-family: "Courier New", monospace; }
h1 { color: gainsboro; }
output b { color: steelblue; }
output em { font-weight: bold; font-style: normal; }
output em.correct { color: green; }
output em.failed { color: red; }
h2 { font-size: 1.1em; margin-top: 2em; color: violet; font-family: sans-serif; font-weight: normal; }

JavaScript

/*
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
::::::::::::::::::::::: CHASE MOSKAL'S COLOR EXTRAVAGANZA ::::::::::::::::::::::::
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
*/


//======================================================
//=========================== COLOR CONVERSION FUNCTIONS
//======================================================


//////
////// HSL to RGB
//////
function hslToRgb (H, S, L) { // H in degrees, S and L in percent
    H = (H%360) / 360;
    S /= 100;
    L /= 100;
    var R, G, B;
    if (S==0) R = G = B = L; // Greyscale
    else {
        var Y = (L < 0.5)
            ? L * (S+1)
            : (L+S) - (S*L);
        var X = (2*L) - Y;
        R = hueToComponent(X, Y, H+(1/3));
        G = hueToComponent(X, Y, H);
        B = hueToComponent(X, Y, H-(1/3));
    }
    return [ // RGB returned as 0-255 integers
        Math.round(R*255), 
        Math.round(G*255), 
        Math.round(B*255)
    ];
}
function hueToComponent (X, Y, H) {
    if (H < 0) H += 1;
    if (H > 1) H -= 1;
    if (H < 1/6) return X + ((Y-X)*H*6);
    if (H < 1/2) return Y;
    if (H < 2/3) return X + ((Y-X)*((2/3)-H)*6);
    return X;
}


//////
////// RGB to HSL
//////
function rgbToHsl (R, G, B) { // integers 0-255
    R /= 255;
    B /= 255;
    G /= 255;
    var max = Math.max(R, G, B);
    var min = Math.min(R, G, B);
    var H, S, L = (max+min) / 2;
    if (max == min) H = S = 0; // monochromatic
    else {
        var delta = max - min;
        S = L < 0.5
            ? delta / (max+min)
            : delta / (2-max-min);
        if (R == max) H = ((G-B)/delta) + (G<B?6:0);
        else if (G == max) H = ((B-R)/delta) + 2;
        else if (B == max) H = ((R-G)/delta) + 4;
        H /= 6
    }
    H *= 360;
    S...