Color Animation

Overview

Learn to create color animation with HTML5. Part of Seven Thunder Software's free online game development course. This tutorial demonstrates how to animate color with HTML5. This article explains RGB colors, how to display the animation, start and stop the timer, along with helpful tips.

Create the Fields

First create the fields needed for color animation. Variables include an array of color values, variables which index into the array, and variables to set the number of times the array cycles.

The Color Array

Use an array where each element in the array represents an RGB color.

An RGB color is a hue and value represented with three componenents. The first component displays Red, The second component displays Green, and the third component displays Blue.

A hexadecimal digit is similar to a decimal digit. Decimal digits are represented with the numbers 0 through 9. For example the set {0,1,2,3,4,5,6,7,8,9}, contains every individual digit available in decimal. Most people are familiar with decimal digits.

Hexadecimal digits are represented with the numbers and letters 0 through F. The set, {0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F}, includes every individual digit available in hexadecimal.

There are more details regarding hexidecimal math, but they aren't necessary for discussing color animation. JavaScript for the color array displays below:

```// Array of colors:
var aCycle = new Array
(
"#00ddff",
"#44aaff",
"#6688ff",
"#8866ff",
"#aa44ff",
"#cc22ff",
"#ee00ff",
"#ff00ff"
);
```

Analyze 00ddff, which is the first number in the array above. The first component 00, represents a value of zero or nothing for the red channel. The second component dd, represents a middle to high value for green. The third component ff, represents the highest value for blue. Therefore the first number in the array is a blue-green.

Every color in the array can be understood in a similar manner. The array declares colors from 00ddff blue-green, to ff00ff red-blue or violet.

The HTML Element to Animate with Color

Animate the foreground text of a `span`, or `div` HTML element. The `id` value for the element is `eText`. The code below uses JavaScript to obtain a reference to `eText`.

```eText = document.getElementById('eText');
```

Color animation will apply to the foreground text of the `eText` element. In the example below, the words Text for Color Animation would change colors during animation. In the example game, the text displays the level and score. Declare the `id` value, eText, in HTML as follows.

```<div id="eText">

Text for Color Animation

</div>
```

Variables to Track Colors

Four variables keep track of the colors as they display. The variables are `nCycleLength`, `nCycleMax`, `nCycleCount`, and `nCycleIdx`. Each variable is a JavaScript `Number` type.

Number `nCycleLength` is the length of our color array. Be sure not violate the boundary of the array during animation. The following line of code saves the length of the color array to number `nCycleLength`.

```nCycleLength = aCycle.length;
```

Number `nCycleMax` represents how many times code will cycle through the array. The following line of code sets the maximum number of times to show the array. Colors in the array will display four times each.

```// Maximum number of
// color cycles to run.
nCycleMax = new Number(4);
```

Number `nCycleCount` tracks the number of times JavaScript code iterates over the color array. At the start of a color animation `nCycleCount` will be set to zero. Each time the entire array of colors displays, increment `nCycleCount`. JavaScript will stop cycling when `nCycleCount` equals `nCycleMax`.

```// Start color animation:
nCycleCount = new Number(0);
```

Number `nCycleIdx` indexes into the color array during animation. The following short listing demonstrates changing the color of the `eText` element with a value from the `aCycle` array.

```eText.style.color = aCycle[nCycleIdx];
...
nCycleIdx++;

```

The Timer

Create a a timer to display each frame of animation at specified time intervals. The timer is assigned with the JavaScript API function:

```setInterval(
function,
time
)
```

The timer is cleared with the JavaScript API function `clearInterval(timer)`.

Function `setInterval()` assigns the time between intervals that a function should be called. The first parameter to `setInterval()` is a user defined function. The user defined function processes one animation frame. The second parameter to `setInterval()` is the amount of time to wait between animation frames. The time parameter represents the time, in milliseconds, to wait between function calls.

The short listing below demonstrates how to instruct JavaScript to call function `colorCycleRun()` every 100 milliseconds.

```timer = setInterval(

function(){
colorCycleRun();
},

100
);
```

When it's time to stop the animation call the JavaScript API function `clearInterval(timer)`. Pass a reference to the currently running `timer` as the only parameter to `clearInterval(timer)`. Assign `timer` to `null`.

Start the Timer

To start the animation initialize the index into our color array to zero. The index is named `nCycleIdx`. Initialize the number of cycles counted so far to zero as well. Variable `nCycleCount` tracks the number of cycles through the color array. Set the interval for the `timer`. Check for a `null` timer to be sure the timer isn't already running. The following listing demonstrates how to start the color animation. Every one hundred milliseconds `colorCycleRun()` should display an animation frame.

```function colorCycleStart(){

nCycleIdx = new Number(0);

nCycleCount = new Number(0);

if (timer == null)
{

timer = setInterval(

function(){

colorCycleRun();

},

100

);

}
}
```

Run the Animation

Now that the timer's set, `colorCycleRun()` should execute every one hundred milliseconds. Function `colorCycleRun()` first verifies code won't overrun the boundaries of the color array. Verify `nCycleIdx` isn't larger than, or equal to, `nCycleLength`. If the value of `nCycleIdx` is too high, then assign zero to `nCycleIdx`. Start iterating over the color array again.

Second determine if code has finished cycling through the array. Test the value of `nCycleMax`. Check `nCycleCount` against `nCycleMax`. If the values are equal then stop the animation. Call `colorCycleStop()`. Function `colorCycleStop()` is explained below.

If the index to the array is in bounds, then assign a color from the array of colors named `aCycle`. Assign the color to the style's `color` property of the HTML element named `eText`. The following listing demonstrates changing the color of the foreground text with JavaScript within function `colorCycleRun()`.

```function colorCycleRun(){

if (nCycleIdx >= nCycleLength)
{

if (nCycleCount >= nCycleMax)
{

colorCycleStop();

return;

}

else {

nCycleCount++;

nCycleIdx = 0
}

}

// Set the foreground color of eText,
// to the value in the aCycle Array.
eText.style.color = aCycle[nCycleIdx];

nCycleIdx++;
}
```

Stop the Timer

To stop the timer, call the JavaScript API function `clearInterval(timer)`, and pass the timer reference as the only argument. Set the timer to `null`. When the timer's `null` then code can restart the color animation. Always assign `null` to the timer, when it's stopped. The value `null` serves as a flag indicating that the timer's not running. If the timer's not `null` then the timer's already running.

```function colorCycleStop(){

if (timer != null){

// Clears the timer
// assigned with setInterval().
// Part of JavaScript
// API predefined functions.
clearInterval(
timer
);

timer = null;

}

eText.style.color = "#ffffff";

}
```

See Surface Game JavaScript Source Code: View for the entire color animation source code.

Tips

Timers

The same JavaScript timer variable can be assigned more than once with `timer = setInterval(...)`. However a JavaScript timer variable can only be cleared once with `clearInterval(timer)`.

Therefore if JavaScript reuses the `timer` variable for more than one call to `setInterval(...)`, then `clearInterval(timer)` will only clear the last timer. All previous timers continue to run. That can use computer processing cycles and perhaps cause unexpected problems.

Prevent multiple timers from running simultaneously. When stopping the timer, assign the value `null`. When starting the timer, verify the timer equals `null`.

Array Boundaries

Code verifies `nCycleCount` is less than `nCycleMax` before assigning a color value from `aColors`. If `nCycleCount` were greater than the number of values in the `aColors` array, then an error would be generated and code wouldn't run correctly.

Summary

This article demonstrated how to create color animation with HTML5. This tutorial explained RGB colors, how to display the animation, starting and stopping the timer, and helpful tips.

Have fun and love learning! For the next tutorial, tap the image icon containing text which says Next Lesson, or the right pointing arrow at the bottom of the page.

Page 7

Game Tutorial for Beginners was prepared a few years ago. HTML5, CSS3, and JavaScript have improved over time, yet this free course continues to include useful features and long standing software development techniques. Enjoy more projects with free Web & game development tutorials.

Tags

free tutorials, learn web design, learn web programming, read books online free, free ebooks, free books online,free books to read, online books, learn web development, STEM, CSS 3, HTML 5, Web developer, learn to code, learn programming, interactive web design, interactive website design,