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);
// 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)
}
}