Canvas HSL Test

Testing of rotating color values for lines using HSL instead of RGB. (much easier)

by mostlygeek

HTML

<html>
<body>
    <h1>About</h1>
    <p>Demonstration of using HSL values to control the lightness 
       of a stroke, thus simulating a nice changing color rotation. </p>
    <p>The advantage of HSL over RBG is a more intuitive control over 
       the color that we want. In this example, the hue does not change
       but the lightness does. This would be much harder to do if we 
       are using RBG values.</p>
    
    <canvas id="myCanvas"></canvas>
</body>
</html>

CSS

h1 { font-size: 2em; }
p { margin: 0.5em;}
#myCanvas {
    border: 1px solid black;
    width: 400px;  /* stretch it */
    height: 200px; 
}

JavaScript

(function() {
    var lastTime = 0;
    var vendors = ['ms', 'moz', 'webkit', 'o'];
    for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
        window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
        window.cancelAnimationFrame =
        window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element) {
        var currTime = new Date().getTime();
        var timeToCall = Math.max(0, 16 - (currTime - lastTime));
        var id = window.setTimeout(function() {
            callback(currTime + timeToCall);
        }, timeToCall);
        lastTime = currTime + timeToCall;
        return id;
    };

    if (!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id) {
        clearTimeout(id);
    };
}());

(function() {
    var canvas = document.getElementById("myCanvas"),
        ct = canvas.getContext("2d");

    canvas.width = 200;
    canvas.height = 200;

    var period = 2 * Math.PI / 1000;  // convert to seconds, PI = 2/second, 2PI = 1/second...
    function drawLine(time, ct, offset, hue) {
        // luminosity of 30% +/- 10%
        var lum = Math.floor(30 + 10 * Math.sin(time * period));

        ct.beginPath();
        ct.strokeStyle = 'hsl(' + hue + ',100%,' + lum + '%)';
        ct.lineWidth = 5
        ct.moveTo(0 + offset, 0);
        ct.lineTo(50 + offset, 200);
        ct.lineTo(100 + offset, 0);
        ct.lineTo(150 + offset, 200);
        ct.lineTo(200 + offset, 0);
        ct.lineTo(250 + offset, 200);

        ct.stroke();
    }

    function draw(time) {
        ct.clearRect(0, 0, 200, 200)
        drawLine(time, ct, -50, 0);
        drawLine(time, ct, -40, 60);
        drawLine(time, ct, -30, 120);
        drawLine(time, ct, -20, 180);
        drawLine(time, ct, -10, 240);
        drawLine(time, ct,   0, 300);

       ...