Animated Butterfly

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

We can create an animated butterfly that is flapping its wings using the setInterval() method.

In this example, we need to use eight images of a  butterfly that flaps its wings at a different stage.

Name the images files as bfly1.gif, bfly2.gif, bfly3gif, bfly4.gif, bfly5.gif, bfly6.gif, bfly7.gif, bfly8.gif.

We need to load the images starting from image1 till image 8 and then repeat the sequence again at a regular interval set by using the setInterval() method.

We declare a global variable i and assign an initial value 0 to it, then use the iteration i+=1 to increase its value one at a time. We reset the value of i back to 0 after its value exceed 9 using the if statement.

We use the following statement to load the images:

var dice = document.getElementById("die");
dice.src="bfly"+i+".gif";

The full script is as follows:

var i=0

var step;
function start(){

myVar=setInterval(rolldice,100);
}
function rolldice(){
i+=1
if (i<9){
var dice = document.getElementById("die");
dice.src="bfly"+i+".gif";
}
else
{i=0}
}
function stop()
{clearInterval(myVar)}

 

</script>

View Animated Butterfly here.

 

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone