Core JavaScript

Animation - Exploding Ball

We can create a simple animation using a timed loop that is generated by recursive calls to the setTimeout(). The setTimeout() function is called with a function and a time passed in as parameters. The function that is passed in is the function that setTimeout() will call after the time interval has expired.

In the example code below, we pass in Loop and 100 so that the function Loop() is called after 100 milliseconds. Since Loop() calls setTimeout() at the end of its execution, it sets up a loop that is executed every 100 milliseconds. This loop creates a timed animation.

Ten images that show a ball in various states of explosion are loaded into an array in the Initialize() function. The image display is cycled as each image is turned off and the next is turned on inside the Loop() function, using the values "none" and "block" for the display property.

Ten img elements are created and styled in the Initialize() function and stored in the array qaBall.

Once these two files are created and saved in the same folder, we can double-click the file "ExplodingBall.html" to begin the animation, as shown below.

ExplodingBall.html

<!DOCTYPE html>
<html>
<head>
  <title>XoaX.net's Javascript Exploding Ball Animation</title>
  <script type="text/javascript" src="ExplodingBall.js"></script>
</head>
<body>
</body>
</html>

ExplodingBall.js

var qaBall = new Array(10);
var iDisplayedFrame = 0;

function Loop() {
  qaBall[iDisplayedFrame].style.display = 'none';
  iDisplayedFrame = (iDisplayedFrame + 1) % 10;
  qaBall[iDisplayedFrame].style.display = 'block';
  setTimeout(Loop, 100);
}

function Initialize() {
  var qpBody = document.getElementsByTagName("body")[0];

  for (var i = 0; i < 10; ++i) {
    qaBall[i] = document.createElement('img');
    qpBody.appendChild(qaBall[i]);
    qaBall[i].src = 'Ball' + (i + 1) + '.png';
    qaBall[i].style.position = 'absolute';
    qaBall[i].style.width = '200px';
    qaBall[i].style.height = '200px';
    qaBall[i].style.display = 'none';
  }

  iDisplayedFrame = 0;
  qaBall[iDisplayedFrame].style.display = 'block';
  Loop();
}

window.onload = Initialize;
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.