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:
  1. The function that is to be called at regular intervals
  2. The interval in microseconds.
The following function will call the changeColor() function every 400 microseconds:
animFlag = setInterval(function() {changeColor()}, 400)
Example
  1. <!DOCTYPE html>
  2. <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta charset="utf-8" />
  5. <script type="application/javascript">
  6. var animFlag;
  7. var counter = 0;
  8. function init() {
  9. var canvas = document.getElementById("canvas");
  10. if (canvas.getContext) {
  11. var ctx = canvas.getContext("2d");
  12. ctx.fillStyle = "#FFFFCC";
  13. animFlag = setInterval(function () { changeColor() }, 400)
  14. }
  15. }
  16. function changeColor() {
  17. var canvas = document.getElementById("canvas");
  18. if (canvas.getContext) {
  19. var ctx = canvas.getContext("2d");
  20. var colour = ["#FFFFCC", "#FFCCCC", "#FF99CC", "#FF66CC", "#FF33CC", "#CC0099", "#993399"];
  21. ctx.fillStyle = color[counter];
  22. counter++
  23. ctx.clearRect(0, 0, 900, 500);
  24. ctx.beginPath();
  25. ctx.moveTo(300, 200);
  26. ctx.lineTo(335, 125);
  27. ctx.lineTo(370, 200);
  28. ctx.closePath();
  29. ctx.fill();
  30. ctx.beginPath();
  31. ctx.moveTo(335, 230);
  32. ctx.lineTo(300, 150);
  33. ctx.lineTo(365, 150);
  34. ctx.closePath();
  35. ctx.fill();
  36. if (counter > 8)
  37. counter = 0;
  38. }
  39. }
  40. </script>
  41. <title>Animation - stars changing colors</title>
  42. </head>
  43. <body onload="init();">
  44. <canvas id="canvas" width="900" height="500"></canvas>
  45. </body>
  46. </html>
Output
First Image
star3.jpg
Second Image
star.html.jpg
Third Image
star1.jpg
And so on; we will get 7 different color stars.