Hexadecimal Color Fading Array

A while ago I wrote a Hexadecimal Color Fading Tutorial explaining how to select a single color at any point on a gradient between two specified colors. In that tutorial there was a function which efficiently broke each of the 2 specified colors into their Red, Green and Blue components and then calculated a single new color at a specified point between them.

Here's what the code looks like:

function fadeHex (hex, hex2, ratio){
    var r = hex >> 16;
    var g = hex >> 8 & 0xFF;
    var b = hex & 0xFF;
    r += ((hex2 >> 16)-r)*ratio;
    g += ((hex2 >> 8 & 0xFF)-g)*ratio;
    b += ((hex2 & 0xFF)-b)*ratio;
    return(r<<16 | g<<8 | b);
}

Approximately 80% of the above code is dedicated to breaking the "hex" and "hex2" hexadecimal colors into their RGB components. Repeatedly calling the above function with the same "hex1" and "hex2" values can be wasteful because the the RGB values are constantly being recalculated and disposed of rather than being stored in variables for quick retrieval.

If you want to create a gradient with a lot of steps or if you want to store your results in an array, you should consider an alternative approach. The following code efficiently creates a gradient of colors between 2 initial hexadecimal values and stores the results in an array.

//
// Returns an array of colors between and including Hex1 and Hex2.
function fadeHex (hex1, hex2, steps){
    //
    // Create an array to store all colors.
    var newArry = [hex1];
    //
    // Break Hex1 into RGB components.
    var r = hex1 >> 16;
    var g = hex1 >> 8 & 0xFF;
    var b = hex1 & 0xFF;
    //
    // Determine RGB differences between Hex1 and Hex2.
    var rd = (hex2 >> 16)-r;
    var gd = (hex2 >> 8 & 0xFF)-g;
    var bd = (hex2 & 0xFF)-b;
    //
    steps++;
    // For each new color.
    for (var i=1; i<steps; i++){
        //
        // Determine where the color lies between the 2 end colors.
        var ratio = i/steps;
        //
        // Calculate new color and add it to the array.
        newArry.push((r+rd*ratio)<<16 | (g+gd*ratio)<<8 | (b+bd*ratio));
    }
    //
    // Add Hex2 to the array and return it.
    newArry.push(hex2);
    return newArry;
}
//
// Store a gradient in an array.
var gradientArray = fadeHex(0x000000, 0xFFFFFF, 2);
//
// Show the contents of the array.
for(var i=0; i<gradientArray.length; i++){
    trace(gradientArray[i].toString(16));
}
// Traces: 0, 555555, aaaaaa, and ffffff.
//

That's pretty slick. But... What if I want to fade between 3 colors? Or 4 colors? Or 6? Calling the above function multiple times might work but it's wasteful for reasons similar to those mentioned in our first code example.

Once again we can improve performance by consolidating multiple function calls into one streamlined function. The tricky part is finding a way to provide arguments to our function in a manner that's both flexible and convenient.

Take a look at the following block of code:

//
//
// "FadeHexes" accepts an array of hexadecimal values separated by numbers which
// specify how many colors are to be generated between hexadecimal values.
//
// For example:
// [0xFF0000,   1,   0x000000,   3,   0xFFFFFF]
// [     Red,   1,      Black,   3,      White]
// would produce:
// [0xFF0000,   0x7F0000,   0x000000,    0x3F3F3F,      0x7F7F7F,     0xbFbFbF,  0xFFFFFF].
// [     Red,   Burgundy,      Black,   DARK-Gray,   MIDDLE-Gray,   LIGHT-Gray,     White].
//
function fadeHexes (arry){
    //
    // Note the length of our array.
    var len = arry.length-1;
    //
    // Create an array to store all colors.
    var newArry = [];
    //
    // For every pair of colors.
    for(var i=0; i<len; i+=2){
        //
        // Note the color pair.
        var hex = arry[i];
        var hex2 = arry[i+2];
        //
        // Add the first color to the array.
        newArry.push(hex);
        //
        // Break the first color into RGB components.
        var r = hex >> 16;
        var g = hex >> 8 & 0xFF;
        var b = hex & 0xFF;
        //
        // Determine RGB differences between the first and second colors.
        var rd = (hex2 >> 16)-r;
        var gd = (hex2 >> 8 & 0xFF)-g;
        var bd = (hex2 & 0xFF)-b;
        //
        // Retrieve number of new colors between first and second color.
        var steps = arry[i+1]+1;
        //
        // For each new color.
        for (var j=1; j<steps; j++){
            //
            // Determine where the color lies between the 2 end colors.
            var ratio = j/steps;
            //
            // Determine RGB values, combine into 1 hex color and add it to the array.
            newArry.push((r+rd*ratio)<<16 | (g+gd*ratio)<<8 | (b+bd*ratio));
        }
    }
    //
    // Add the last color to the end of the array.
    newArry.push(arry[len]);
    //
    // Return the new array of colors.
    return newArry;
}
//
// Store a gradient in an array.
var gradientArray = fadeHexes([0xFF0000,   1,   0x000000,   3,   0xFFFFFF]);
//
// Show the contents of the array.
for(var i=0; i<gradientArray.length; i++){
    trace(gradientArray[i].toString(16));
}
//
// Traces: ff0000, 7f0000, 0, 3f3f3f, 7f7f7f, bfbfbf, and ffffff.
//
//

Now that's pretty handy! The "fadeHexes" function lets you specify a gradient with any number of colors and any number of steps between each color. Neato.

If you're curious, the SWF at the top of this page was created with code similar to the following:

//
//
function fadeHexes (arry){
    var len = arry.length-1;
    var newArry = [];
    for(var i=0; i<len; i+=2){
        var hex = arry[i];
        var hex2 = arry[i+2];
        newArry.push(hex);
        var r = hex >> 16;
        var g = hex >> 8 & 0xFF;
        var b = hex & 0xFF;
        var rd = (hex2 >> 16)-r;
        var gd = (hex2 >> 8 & 0xFF)-g;
        var bd = (hex2 & 0xFF)-b;
        var steps = arry[i+1]+1;
        for (var j=1; j<steps; j++){
            var ratio = j/steps;
            newArry.push((r+rd*ratio)<<16 | (g+gd*ratio)<<8 | (b+bd*ratio));
        }
    }
    newArry.push(arry[len]);
    return newArry;
}
function fillScreen (hexColors){
    var len = hexColors.length;
    var wi = Stage.width;
    var hiStep  = Stage.height/len;
    for(var i=0; i<len; i++){
        beginFill(hexColors[i]);
        moveTo(0, i*hiStep);
        lineTo(0, i*hiStep+hiStep);
        lineTo(wi, i*hiStep+hiStep);
        lineTo(wi, i*hiStep);
        lineTo(0, i*hiStep);
    }
    endFill()
}
function drawCircles (hexColors){
    var len = fadedColors.length;
    var around = Math.random();
    var outside = 20+Math.random()*150;
    var inside = Math.random()*100;
    for(var i=0; i<len; i++){
        var r = i/len;
        lineStyle(256-r*256, fadedColors[i]);
        var arou = i*around*2*Math.PI;
        var awa = inside+outside*(1-r);
        var xx = Stage.width/2 + Math.cos(arou)*awa;
        var yy = Stage.height/2 + Math.sin(arou)*awa;
        moveTo(xx, yy);
        lineTo(xx+.5, yy);
    }
}
function drawStuff(){
    var color1 = Math.random()*0xFFFFFF;
    var gap1 = Math.floor(Math.random()*50);
    var color2 = Math.random()*0xFFFFFF;
    var gap2 = Math.floor(Math.random()*30);
    var color3 = Math.random()*0xFFFFFF;
    fadedColors = fadeHexes([color1, gap1, color2, gap2, color3]);
    clear();
    fillScreen (fadedColors);
    drawCircles (fadedColors);
}
//
//
Stage.align = "TL";
drawStuff();
setInterval(drawStuff, 3000);
//
//

If you like the spiraling circles you can read more about spirals in my Logarithmic and Archimedean spiral tutorials.

I hope you find the code for generating color gradients as fun and useful as I did.

8 Responses to “Hexadecimal Color Fading Array”

  1. Wilson Silva says:

    Thanks man, I really needed this.

  2. Blair says:

    wow very usefull stuff.
    thanx so much for sharing this !

  3. roberto says:

    ah thanx, it was the AS3, it needs to be put on AS2 thanks again, great script

  4. Pixelwit says:

    @Roberto, You might need to set your Publish settings to AS2 rather than AS3. You can do that by using the top menu in Flash. Choose File/Publish-Settings/Flash-tab/script and then select AS2.

  5. roberto says:

    hi i was just trying your script (cool one) but i cant get it 2 work im pasting it on my action panel on the first frame of the scene (CS3) but when i play it 2 c the swf, i only get the output with the code for the colors but nothing on the SWF… help would be great

  6. […] This tutorial uses some of the code and concepts from my previous Color Gradient and Circle Drawing tutorials so I highly recommend checking them out for a more in-depth […]

  7. […] some colorful images from the SWF used in the Hexadecimal Color Fading Array article. I like how almost any 3 random colors seem to go together well when used in a […]

  8. […] I hope you find this color fading code as handy as I did. If you’d like to read more about storing your color fades in an array you can read my Fading Multiple Colors Tutorial. […]

Leave a Reply

PixelWit.com's Comment Guidelines

© Sean O'Shell 2007-2017
css.php