Canvas Animation
In this article, we will learn how to create basic animation using HTML5 canvas and JavaScript.
Continuously changing the color of a Star (Twinkling of the star)
To make this work, we will first write a function that:
1. Clears the screen
2. Draws the star in a different color by going through an array of colors. The color changes will be continuous.
Step 1
We will first create a "changeColor()" method. In this method, we will create an array of colors that the star will go through.
var color = ["#FFFFCC", "#FFCCCC", "#FF99CC", "#FF66CC","#FF33CC","#CC0099","#993399"];
Step 2
Assign a color to the fillStyle method, and increment the counter variable, as in the following:
ctx.fillStyle = color[counter];
counter++;
Step 3
Clear the screen so that we don't keep drawing over an already drawn star, as in the following:
ctx.clearRect(0,0,900,500);
Step 4
If we have reached the end of the color array, reset the counter to make the star twinkle again by changing the color, as in the following:
if(counter>13)
counter = 0;
Now that we have the function, we must call it repeatedly at set intervals. We will use the "setInterval()" method for this. The setInterval takes 2 parameters:
- The function that is to be called at regular intervals
- The interval in microseconds.
The following function will call the changeColor() function every 400 microseconds:
animFlag = setInterval(function() {changeColor()}, 400)
Example




Join the conversation! Your thoughts help the community grow.