Indexed Color Animation Tutorial

Implement Fast, Lightweight, Visual Effects

Animated Coffee Example Introduction What's an Indexed Graphic? Percolator Image Color Preparation JavaScript Explained HTML Explained Tips Summary Source Code More Color Tutorials!

Introduction

Learn to create color animation behind indexed graphics, for fast download time with unique visual effects. This tutorial explains some differences between indexed and true color graphics. With JavaScript and HTML5 features, developers and designers can extend the color range of an indexed graphic. This article discusses techniques to prepare animated color for use with JavaScript.

What's an Indexed Graphic?

An eight bit or indexed image displays a maximum of 256 colors, including transparency. An eight bit graphic applies 28 colors to a color table or palette. 28 equals 256. Eight bit graphics display a maximum of two hundred and fifty six colors. Indexed graphics are often lightweight and download quickly because indexed images usually require relatively small file sizes.

Indexed graphics are most efficent with solid blocks of color. Some algorithms save the color value with the number of pixels which use the color value. For example assume a 640 x 480 image included a clean crisp solid color background. Some rows of color might cross the screen with 640 pixels. Yet storage for the entire row saves just one color, and one number, representing how many times to repeat the color. Indexed graphics have the option to save just two entries for large sections of a graphic.

Eight bit graphics are often called indexed graphics because code accesses colors by index into a color palette. The palette's 256 color restriction makes indexing somewhat efficent.

Indexed Graphic Disadvantages

Very complex eight bit graphics can require large file sizes. Sometimes JPG images with true color compress similar graphics to smaller file sizes, than indexed graphics. Indexed images provide the greatest savings only when contiguous sections apply the same color.

Additionally 24 bit JPG, PNG, and other image file formats, with the option to save larger numbers of colors, often provide the most realistic and colorful results. Preparing realistic indexed graphics takes some skill, and at times may seem impossible.

True Color Images

So called, true color images, such as JPG 24 bit and PNG 24 or 32 bit images, display up to 224 or 232 colors. 224 equals 16,777,216 colors. 232 equals 4,294,967,296 colors. However increased colors add to both file size and download time. Despite the name, true color, the human eye can see up to 100 million different hues, shades, and tints. 224 images prepare just 16,777,216 colors. 232 images prepare the same number of colors as 224 images, yet offer levels of transparency as well.

Consider using 256 color image files with JavaScript or WebGL visual effects, to speed download time and render awesome VFX. The Animated Coffee example, with a lightweight indexed image, demonstrates a useful technique. Prepare a small eight bit graphic, yet apply JavaScript to render the full range of Web available colors.

Percolator Image

The coffee pot displays in the following graphic. Gray and white checkers represent transparent areas.

Percolator with Transparent Areas

Color Cycling

JavaScript color cycling refers to color changes to background or foreground HTML elements, over time. The term cycling indicates reuse of colors. Code interates over an array of colors. Sometimes colors from the array display multiple times during one animation sequence.

This tutorial demonstrates one method to add unique color animation to a Web page.

Color Preparation

Ideally colors change gradually over time with natural animation. Additionally, both the last and first colors of the cycle should display a subtle difference in color only. Any major difference in color between the last and first color of the array causes a jump in color between each cycle.

There are many ways to create a range of colors for display during animation. Some applications work best with dynamic color preparation, a manually configured color array, a color generator, or graphic software preparation. The Animated Coffee Example displays with a manually configured color array. With patience even the manual method can display much more sophisticated, smooth, and visually amazing examples. There are pros and cons to most approaches.

Dynamic Color Preparation

A dynamic color array is a list of colors created when needed with JavaScript within the current application. Code might prepare the array when the Web page loads or in response to user interaction. Dynamic color might also process individual colors as the animation runs, instead of using a predefined array.

Creating numbers on the fly might take less time to download. The JavaScript file itself should be smaller because it doesn't contain an array of color values. However, computations can be expensive. The computer will have to process more operations to create the colors, before they display.

If your script runs on mobile devices it's helpful to minimize use of processing power. Not all smart phones can handle many function calls and mathematical operations.

Manually Configured Color Array

Prepare a color array manually with hexadecimal colors and a text editor. Later display the colors with some JavaScript to see how they look. However changing RGB values in JavaScript, then running the animation to see the colors, can take some time.

Color Generator

Perhaps the best option to create gradually changing natural colors is to program a color generator separately, then store the colors in an array. For example, create a JavaScript program which creates color channel values, then saves those values in a file. The generator might gradually change blue, then green, then red values for smooth transitions.

The JavaScript API function Math.sin(), returns values between -1.0 and 1.0. An array generator could gradually modify values for the red, green, and blue portions of an RGB color array, based on angular input, and cyclical output from the sin function.

Graphic Software Preparation

The Coffee Pot Animation Example uses a prepared array of colors. The colors were simply added manually with some guess work. However Photoshop's much more helpful in determining which colors to add to the array. The Color Picker dialog box, allows designers to visually adjust color channels, then select hexadecimal colors from the hexadecimal field in the dialog.

Additionally Adobe Illustrator saves gradients to SVG editable text format. Consider creating gradients visually with Illustrator, save the SVG file, then copy and paste values into JavaScript.

JavaScript

Most examples use a timer to assign the amount of time to wait between rendering distinct colors from an array. The Coffee Pot Animation Example initializes a timer to start the color cycle animation. However, remember to stop the timer after a few cycles, too.

The short listing below creates a timer which calls function colorCycleRun(), every 64 milliseconds.

timer = setInterval(
 function(){
  colorCycleRun();
 },
 64
);		

The Coffee Pot Animation Example uses an HTML id to obtain a reference to the image element. Store a reference to the image because the image's background changes colors over time. The coffee pot img element's id value is simply a. The following short listing demonstrates saving a reference to the coffee pot's HTML image element.

elemA = document.getElementById(
 'a'
); 		

Save a variable with the length of the array of colors. Use the length of the array to avoid running beyond the boundaries of the array. Create an index for iterating over the color array. Create a variable with the maximum number of loops to run the animation. The Coffee Pot Animation Example runs through the array three times, then stops. The following short listing prepares a set of variables for use during animation.

// The maximum size of the array:
var iCycleArrayLength = aCycle.length;

// The number of times 
// to cycle through the array:
var iCycleMax = new Number(
 3
);

// Current index into the array,
// while rendering the cycle:
var iCycle = new Number(0);  	

Create a function to start color cycling and another function to stop color cycling. In the following listing, function colorCycleStart() begins the animation. Function, colorCycleStop() ends the animation.

/**
 Start the animation.
**/
function colorCycleStart(){
// Index during
// animation:
iCycle = 0; 		

// Animation
// cycle count
// while playing.
iCycleCount = 0;	

timer = setInterval(

 function(){
  colorCycleRun();
 },
 64
);	
}

/**
 Stop the animation.
**/
function colorCycleStop(){

 if (timer != null){

 clearInterval(
  timer
 );

 timer = null;  			
} 

}

Copy Colors Behind the Image

Create a function which copies colors from the array to the image's background. The following line of code assigns the color at index, iCycle, from array, aCycle, to the background style of image reference, elemA.

elemA.style.backgroundColor = aCycle[iCycle]

The following listing displays one animation frame. The timer calls function, colorCycleRun(), every sixty four milliseconds. If the number of cycles through the array is greater than or equal to iCycleMax, then color animation stops. Function colorCycleRun() then calls colorCycleStop().

function colorCycleRun(){

if (iCycle > iCycleArrayLength){

 if (iCycleCount >= iCycleMax){

  colorCycleStop();

  return;

 }

 else {
 
  iCycleCount++; 
  
  iCycle = 0;
  
 }
}	

iCycle++; 
 		
elemA.style.backgroundColor = aCycle[iCycle];  
				
}	

HTML

In HTML create an image to display the animated colors. Give the image an id attribute and a source file.

<img 
 
 id="a" 

 onclick="colorCycleStart()"

 src="../assets/percolator-transparent.gif" 

 alt="Coffee Color Cycling"

/>	

Add a couple of buttons to manually start or stop the animation. Button onclick event handlers activate start and stop functions.

<div>

<button 
 onclick="javascript:colorCycleStart()" 
>

Start 

</button>

<button 
 onclick="javascript:colorCycleStop()" 
> 

Stop 

</button>

</div>

Tips

Colors for Mood and Surroundings

Select colors that work well with surrounding graphics. The right colors fit the animation's mood.

Creativity

The Animated Coffee example, applies a fully transparent GIF coffee pot, allowing dynamic color to render in the coffee pot but not the percolator. Consider much more sophisticated color schemes and graphical combinations, such as lightning strikes, storms, or blinking neon signs. Any HTML element, with a background or foreground style property, can receive animated color.

Gradual Color Changes

A longer array with less change between colors provides smoother animation. A timed break between color cycles can provide a natural resting point.

Summary

This tutorial demonstrated one technique to create color animation with JavaScript color cycling and indexed graphics. Website development benefits from visual effects which initialize quickly.

The Animated Coffee example, changes colors inside a coffee pot. The colors are kind of silly, not representing real coffee.

This tutorial explained how to prepare colors and implement color cycling within a lightweight indexed eight bit graphic. Colors show through completely transparent areas in the image. The article also covered some differences between eight bit, twenty four bit, and thirty two bit images.

See more color for the Web examples. See the Indexed Color Animation source code.

Copyright © 2015 Seven Thunder Software. All Rights Reserved.