Falcon80 Logo
 
Making a star twinkle

Do you like how the star twinkles above? It's pretty simple. The trick is to change the colours of the star in a way that makes it appear as if it is twinkling.

To make this work, we will first write a function that

1. Clears the screen
2. Draws the star in a different colour by going through an array of colours. The colour changing will be cyclic.

function changeColor()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");

// Create an array of colours that the star will go through
var colour = ["#FFFFCC", "#FFFFBB", "#FFFFAA", "#FFFF99","#FFFF66", "#FFFF00", "#FFFF00","#FFFF11","#FFFF22", "#FFFF33", "#FFFF66", "#FFFF99" ]

// Assign a colour to the fillStyle method, and increment counter variable
ctx.fillStyle = colour[counter];
counter++

Clear the screen so that we don't keep drawing over an already drawn star.
ctx.clearRect(0,0,900,500);

//Draw the star.
ctx.beginPath();
ctx.moveTo(300,200);
ctx.lineTo(335,125);
ctx.lineTo(370,200);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(335,230);
ctx.lineTo(300,150);
ctx.lineTo(365,150);
ctx.closePath();
ctx.fill();

// If we have reached the end of the colour array, reset counter to make the twinkling cyclic.
if(counter>13)
counter = 0;
}
}
 

Now that we have the function, we have to 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

setInterval(function() {changeColor()}, 400)

The above function will call changeColor() function every 400 microseconds.


Now, let's put it all together

HTML Code
<html>
<head>
  <script type="application/javascript">
var animFlag;
var counter = 0;

function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
ctx.fillStyle = "#FFFFCC";
animFlag = setInterval(function() {changeColor()}, 400)
}
}

function changeColor()
{
var canvas = document.getElementById("canvas");
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
var colour = ["#FFFFCC", "#FFFFBB", "#FFFFAA", "#FFFF99","#FFFF66", "#FFFF00", "#FFFF00","#FFFF11","#FFFF22", "#FFFF33", "#FFFF66", "#FFFF99" ];
ctx.fillStyle = colour[counter];
counter++
ctx.clearRect(0,0,900,500);
ctx.beginPath();
ctx.moveTo(300,200);
ctx.lineTo(335,125);
ctx.lineTo(370,200);
ctx.closePath();
ctx.fill();
ctx.beginPath();
ctx.moveTo(335,230);
ctx.lineTo(300,150);
ctx.lineTo(365,150);
ctx.closePath();
ctx.fill();
if(counter>13)
counter = 0;
}
}
</script>
  <title>Animation - stars changing colours</title>
</head>
</html>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas>
</body>
</html>