Photoshop Color Picker Gradient I'm trying to improve my Color Picker code.  It works like Photoshop and I don't want to use a library.

    for(var yColor = 0; yColor &lt; 255; yColor++)
    {
        var r = 255,
            g = 0,
            b = 0;
        for(var xColor = 0; xColor &lt; 255; xColor++)
        {
            if(r == 255 &amp;&amp; g &lt; 255 &amp;&amp; b == 0) g += 6;
            else if(r &gt; 0 &amp;&amp; g == 255 &amp;&amp; b == 0) r -= 6;
            else if(r == 0 &amp;&amp; g == 255 &amp;&amp; b &lt; 255) b += 6;
            else if(r == 0 &amp;&amp; g &gt; 0 &amp;&amp; b == 255) g -= 6;
            else if(r &lt; 255 &amp;&amp; g == 0 &amp;&amp; b == 255) r += 6;
            else if(r == 255 &amp;&amp; g == 0 &amp;&amp; b &gt; 0) b -= 6;

            if(r &gt; 255) r = 255;
            else if(r &lt; 0) r = 0;
            else if(g &gt; 255) g = 255;
            else if(g &lt; 0) g = 0;
            else if(b &gt; 255) b = 255;
            else if(b &lt; 0) b = 0;

            var rG = r + yColor &gt; 255 ? 255 : r + yColor;
            var gG = g + yColor &gt; 255 ? 255 : g + yColor;
            var bG = b + yColor &gt; 255 ? 255 : b + yColor;

            GAContext.beginPath();
            GAContext.fillStyle = "rgb(" + rG + ", " + gG + ", " + bG + ")";
            GAContext.rect(xColor, yColor, 1, 1);
            GAContext.fill();
        }
    }
If I redraw it, It become a bit laggy.


In my tests, using createImageData and putImageData to fill the individual pixels ran about 3x faster than rect and fill.

You can replace this code:

GAContext.beginPath();
GAContext.fillStyle = "rgb(" + rG + ", " + gG + ", " + bG + ")";
GAContext.rect(xColor, yColor, 1, 1);
GAContext.fill();


With this:

pixelData[0] = rG;
pixelData[1] = gG;
pixelData[2] = bG;
GAContext.putImageData(pixel, xColor, yColor);


And before the loop, add this:

var pixel = GAContext.createImageData(1, 1);
var pixelData = pixel.data;
pixelData[3] = 255;


Test it out here. This Stack Overflow question is relevant. You may also be able to figure out a clever way to do this with gradients that would be much faster.