Jump to main content

Follow the Bouncing Ball: A Web Animation Project

1
2
3
4
5
154 reviews

Abstract

This project is a fun way to try your hand at programming. You'll learn how to create some simple animations, and you'll perform tests and make measurements to help you create more realistic-looking animations. All you need to get started is a Web browser and a text editor (like Notepad).

Summary

Areas of Science
Difficulty
 
Time Required
Short (2-5 days)
Prerequisites
Familiarity with Web browser and text editing programs
Material Availability
Readily available
Cost
Very Low (under $20)
Safety
No issues
Credits
By Nate Brogan, Symantec
Edited by Andrew Olson, Ph.D., Science Buddies

Objective

The goal of this project is to investigate the effects of timing interval and step size on perceived animation smoothness. You will write a simple JavaScript program that will move an object around on a Web page. This project will help you create more advanced Web pages that could have any type of animation.

Introduction

This is an example of a first-time programming project. You will be writing a basic animation program that will move an object around on your computer screen, on a Web page in your browser window. The project uses JavaScript, an interpreted programming language supported by most Web browsers. You will learn how to write an HTML file containing your program, and how to load and run the file in your browser. You'll also learn how to control the motion of the object, and you will experiment with different settings to see the effect on apparent smoothness of the motion.

Preliminaries

These are things you need to know before you get started.
  1. You'll need to write your file with a text editor, which is a program that can save plain text files. The "Notepad" program that comes with Windows will do just fine. You should not use a word processing program (e.g., Word), because word processors do not save files as plain text by default.
  2. JavaScript is a programming language for web pages, so the HTML file you will be writing is like a simple web page. Here is the basic format of an HTML file: <!-- comment line: ignored by browser, use these as notes to yourself about your program -->
    <HTML>
    <HEAD>
            [Title and JavaScript functions go here.]
    </HEAD>

    <BODY>
            [The parts you want to appear on the page go here.]
    </BODY>
    </HTML>

    HTML uses tags to designate various parts of the document. Tags are enclosed by the characters "<" (less-than sign) and ">" (greater-than sign). The first line is a comment, enclosed by "<!--" and "-->". Comments in an HTML file are ignored by the browser, so you can use them as notes to yourself. They can help you remember what the different parts of your program are supposed to do. You need the tag "<HTML>" at the beginning. The document has two sections, a HEAD section, which contains general information about the document, and a BODY section which contains the displayed material. The HEAD section is where you would specify the title of the document, and also where you would put JavaScript functions used in the document. The end of the HEAD section is indicated by the end tag, "</HEAD>". Next comes the BODY section, with material that you wish to appear on the page. It is ended by the end tag "</BODY>". Finally, the end of the document is indicated by the HTML end tag, "</HTML>". The same pattern applies to all HTML tags: the end tag is made by adding "/" (the forward slash character) to the beginning of the corresponding start tag.
  3. For practice, try using your text editor to write a very simple HTML file like the one below. (You can write it yourself, or you can copy and paste from your browser to your text editor.)

    <!-- Science Buddies: HelloWorld.html -->
    <HTML>
    <HEAD>
       <TITLE>Hello, world!</TITLE>
    </HEAD>

    <BODY>
       Hello, world!
    </BODY>
    </HTML>
  4. Use your text editor to save the file. Call it something like "HelloWorld.html" (when choosing a name for your file, always end the name with ".htm" or ".html").
  5. Now open your HelloWorld.html file with your browser. In your browser, use the "File" menu, and choose the option "Open..." (for Firefox, choose "Open File..."). Using the controls in the File Open dialog box that pops up, navigate to your file and select it. In Windows, you can also open the file by right-clicking it, selecting "Open with..." and then choosing a web browser from the list of available programs. You should see "Hello, world!" on both the browser title bar and on the body of the page.

Getting Started with JavaScript

Now that you've succeeded with writing an HTML file and opening it with your browser, you're ready to delve into JavaScript. The following link has a step-by-step tutorial that will give you a great introduction to JavaScript programming: http://www.webteacher.com/javascript/index.html. Note that this tutorial contains additional, advanced information that you will not necessarily need for this project.

Writing a JavaScript Animation The rest of the Introduction will cover the pieces that you need to write an animation program in JavaScript:
  1. a function, to control the timing and placement of the image on the page,
  2. one or more HTML image objects to move on the page,
  3. a JavaScript object (that is, a way to refer to the HTML object(s) in JavaScript), and
  4. a timer, to update the page at regular intervals.
Once you have put all these together, you will be able to start exploring how changing the settings affects the appearance of the animation.

A JavaScript Function

As you learned in the tutorial, JavaScript uses functions. Functions can do nearly anything you want them to do. Your function will contain code that will run your animation. A function in JavaScript looks like this:
// This is an example of a single-line JavaScript comment.
// Below is an example of a multi-line JavaScript comment.
/* This function doesn't do anything useful yet,
   but we will add code later to make it work.*/

function myFunction()
{
/* Your animation code will go here */
}

Here is how to put the JavaScript function into an HTML file. The function is included in the <head> section of the HTML file, like this:
<HTML>
<HEAD><TITLE>My HTML</TITLE>
<!-- saved from url=(0030)http://www.sciencebuddies.org/ -->
<!-- When this code is saved as a local file, the preceding line tells Internet Explorer to treat this file according to the security rules for the Internet zone (plus any security rules specific for the Science Buddies website). -->
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript1.2">
<!--
// This is an example of a single-line JavaScript comment.
// Below is an example of a multi-line JavaScript comment.
/* This function doesn't do anything useful yet,
   but we will add code later to make it work.*/

function myFunction()
{
/* Your animation code will go here */
}
// -->
</SCRIPT>
My Page
</BODY>
</HTML>

An HTML Image Object

Your function will need an object to animate. For this example, we will keep it simple. We will use a ball as an object. To get your object, right click on the red ball (below), and do a "Save As..." Save the ball image as ball1.gif, in the same directory as your HTML file. (Note: if you choose a different filename, you will also have to change the name in the HTML <IMG> tag, below.) Here is the ball image for you to save:

Pixelated image of a red circle

Now we will add the ball to your HTML file by inserting the following text just after <BODY>:
<IMG ID="ball" STYLE="position: absolute; left: 200; top: 200; width: 10; height: 10;" SRC="ball1.gif">

Save your HTML file and open it in the Web browser. You should see the little red ball on your Web page. The ball should be 10 pixels wide. It should be located 200 pixels from the top of the Web page and 200 pixels from the left edge of the page. You can try changing the way your ball looks by changing the value of left, top, width, and height. For example, if you want a bigger ball, you can change the width and height from 10 to 50. Prove to yourself that it works. Try changing some of these values, saving the HTML file, and opening the file in a browser.

An Object in JavaScript

The object from step 2 is an HTML image object. We need to be able to use this object in JavaScript, so we have to create a JavaScript variable to represent the ball. Add this variable on the line before myFunction.

var myBall;

The statement above creates the variable, next we have to assign a value to the variable. That is, we have to tell JavaScript that myBall should represent the HTML object "ball." To do this, we use a built-in JavaScript object called document. We can use document to get an HTML object by its ID. To do this, replace the last line you added with:

var myBall = document.getElementById("ball");

This line tells JavaScript to look in the HTML document and find the object, or element, with the ID "ball," and assign it to the JavaScript variable myBall. You will notice in the HTML our ball has the ID of "ball." Now JavaScript knows about the ball in the Web page.

The Time

Animation requires that we change something on an interval. For example, we may want to change the position of the ball every five seconds, or change the color every ten seconds. We will tell JavaScript to call our function, on an interval so we can change something. To accomplish this add the following call to the built-in JavaScript method, "setInterval" (add this line before the code for myFunction()):

setInterval("myFunction()", 200);

This line tells JavaScript to run myFunction every 200 milliseconds. Right now, myFunction does not do anything. So let's add animation code to myFunction.

Writing a Simple Animation Function in JavaScript

For the first animation example, we will have the ball keep moving down the screen. First we need another variable to keep track of our current location. Add this variable after the myBall variable:

var loc = 200;

Add this code between the braces of myFunction:

loc += 10; // This adds 10 to the value of loc
myBall.style.top= loc; // This moves the ball

In this case we are changing one of the properties of the ball. The property is style.top. We can change this property to make the ball move up or down.

Now save your HTML file, and open it in your Web browser. You should see your ball keep moving down the screen. You have just created an animated Web page! If your page is not working, here is the entire HTML file:

<HTML>
<HEAD><TITLE>My Html</TITLE>
<!-- saved from url=(0030)http://www.sciencebuddies.org/ -->
<!-- When this code is saved as a local file, the preceding line tells Internet Explorer to treat this file according to the security rules for the Internet zone (plus any security rules specific for the Science Buddies website). -->
</HEAD>
<body>
<IMG ID="ball" STYLE="position: absolute; left: 200; top: 200; width: 10;" SRC="ball1.gif">
<SCRIPT LANGUAGE="JavaScript1.2">
<!--

var myBall = document.getElementById("ball");
var loc = 200;

setInterval("myFunction()", 200);

function myFunction()
{
   loc += 10; // This adds 10 to the value of loc
   myBall.style.top = loc; // This moves the ball
}

// -->
</SCRIPT>
My Page
</BODY>
</HTML>

Improving the Animation Function: A Bouncing Ball

Just having a ball move down of you Web page may not be very exciting. We can make the ball move up and down by using a variable to determine the direction the ball is moving. Once it reaches an upper limit or a lower limit, we will make it turn around. Add the variable direction to the line above myFunction:

var direction = 0;

We will use this variable called direction so we know which way the ball is moving. 0 means the ball is moving down, and 1 means the ball is moving up. Try replacing myFunction with this new myFunction (to keep your previous work, save the HTML file with a new name):

function myFunction()
{
   if(0 == direction)
   {
      /* move down */
      loc += 10;

      if(loc >= 500)
      {
         /* reached lower limit, change direction */
         direction = 1;
      }
   }
   else
   {
      /* move up */
      loc -= 10;

      if(loc < 10)
      {
         /* reached upper limit, change direction */
         direction = 0;
      }
   }

   myBall.style.top = loc;
}

Going Further

The goal of this project is to determine the best settings for the timer interval and ball step size in order to produce the smoothest animation. You can make the project even better by going further with your investigation of animation. The Variations section, below, has some suggestions to get you thinking.

Note for JavaScript files with Internet Explorer:
If you experience difficulty running your JavaScript code in Internet Explorer, we strongly suggest that you install the Firefox web browser and use it instead of Internet Explorer. For more information or to download the Firefox installer, see: http://www.mozilla.com/firefox/.

If you want to continue to use Internet Explorer, try adding the following line at the beginning of your file:
<!-- saved from url=(0014)about:internet --> This line will cause Internet Explorer to run your file according to the security rules for the Internet zone on your computer. In our experience this may work, or it may not. For more information see http://www.phdcc.com/xpsp2.htm.

Terms and Concepts

To write a simple program in JavaScript, you should do research that enables you to understand the following terms and concepts: Questions:

Bibliography

  • You can find a step-by-step JavaScript tutorial at the link below. After studying the tutorial, you should be able to answer all of the questions listed above, and you'll be ready to write a simple calculator. Webteacher Software. (2006). JavaScript Tutorial for the Total Non-Programmer. Webteacher Software, LLC. Retrieved June 6, 2006.
  • Introduction to Programming by Matt Gemmell describes what programming actually is: Gemmell, M. (2007). Introduction to Programming. Dean's Director Tutorials & Resources. Retrieved March 14, 2014.
  • HTML Forms reference: W3C. (1999). Forms in HTML Documents, HTML 4.01 Specification. World Wide Web Consortium: Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University. Retrieved June 6, 2006.
  • A list of reserved words in JavaScript (you cannot use these words for function or variable names in your program, because they are reserved for the programming language itself): JavaScript Kit. (2006). JavaScript Reserved Words. Retrieved June 6, 2006.
  • A JavaScript reference: Mozilla Developer Network and Individual Contributors. (2013, December 14). JavaScript reference. Retrieved March 14, 2014.
  • If you get interested and start doing a lot of web development, you may want to use a text editor that is a little more sophisticated than Notepad. An editor designed for web development and programming can help with formatting so that your code is more readable, but still produce plain text files. This type of editor can also fill in web-specific HTML coding details and do "syntax highlighting" (e.g., automatic color-coding of HTML), which can help you find errors. Search online for "free HTML editor" to find one.

Materials and Equipment

To do this experiment you will need the following materials and equipment:

Experimental Procedure

Adding Variables

The goal of this project is to determine the best settings for the timer interval and ball step size in order to produce the smoothest animation. The script you created in the Introduction section has hard-coded numbers for these quantities. It will be much more convenient to change these values if you add variables for the timer interval and the step size for the motion of the ball. This way, you will only need to change the value in one place, when the variable is assigned a value, rather than searching for a hard-coded value in multiple places throughout the script.
  1. It will be much more convenient to change these values if you add variables for the timer interval and the step size to control the motion of the ball.
  2. You can make it even easier to change the values of the variables by adding a <FORM> section to your HTML page, with <INPUT> fields linked to the script variables. With this feature, you'll be able to change the values right in your Web browser program, rather than having to use a text editor to change the HTML file. It's not hard to do, and you can learn all about it by checking out this project: Forms and Functions: Writing a Simple Calculator Program with JavaScript.

Calculating Time

The next thing to do is to verify that your timer interval is working as you expect. For instance, there may be some timer settings that are too fast for your browser program to keep up with. For each of the timing intervals you wish to use in your experiment, you need to run a test like the one described below.

  1. As our example, we will use the final animation function presented in the Introduction. This is the one where the ball changes direction, bouncing up and down from 0 to 500 pixels.
  2. When you start the Web page, the ball will be moving down. At the moment the ball turns around and starts moving up, start your stopwatch. Stop it at the moment the ball reaches the top of the Web page. How long did it take?
  3. Now let's do some math to determine how long it should have taken. We set the interval to 200 milliseconds. On each interval we said to move the ball 10 pixels. That means the ball should move 50 pixels every second. How did we determine this?
    10 pixels / 200 milliseconds
    = 10 pixels / 0.200 second
    = 50 pixels / second.
    Now we know the speed of the ball. How long should it take for the ball to move from the bottom to the top (500 pixels)?
  4. How close were the timed results to your calculated results? (For a timer interval of 200 ms and a distance of 500 pixels, they should agree pretty well.)
  5. For each timer interval that you wish to use for your experiment, run a similar test. For shorter timer intervals, you will need to also decrease the step size (or increase the total distance traveled, or count more than one "bounce") in order to have enough time elapse so that you can measure it accurately.
Measuring Smoothness
  1. You'll need to figure out a rating scale to measure "smoothness." Start out by making observations at different settings:
    • Do you see multiple images or a single image of the ball?
    • Does the ball appear clearly, or is it fuzzy? (Maybe a little bit of blur makes the animation more realistic?)
    • Is the motion really jumpy?
  2. Once you have an idea of the range of effects, assign a rating scale from 1 to 5, low scores being poor ratings and high scores being excellent ratings.
  3. If you have some willing helpers available, ask them for their perceptions. Explain your rating scale and have them rate the smoothness with the same settings you try (see below).
Collecting and Analyzing Your Data
  1. Systematically explore combinations of timer interval and step size in order to find the best settings for your animation. (Remember to verify that the desired timer settings actually work as you expect.)
  2. For example, you could try a series of step sizes that increase by a factor of 2: 1, 2, 4, 8, 16, 32 pixels, etc.
  3. You can do a similar series of timer steps.
  4. Try each possible pair of settings, and rate the smoothness of the animation.
  5. Make graphs of your smoothness rating as a function of step size and timer interval.
  6. Which combinations work best? Is there more than one group of settings that works reasonably well?
icon scientific method

Ask an Expert

Do you have specific questions about your science project? Our team of volunteer scientists can help. Our Experts won't do the work for you, but they will make suggestions, offer guidance, and help you troubleshoot.

Global Connections

The United Nations Sustainable Development Goals (UNSDGs) are a blueprint to achieve a better and more sustainable future for all.

This project explores topics key to Industry, Innovation and Infrastructure: Build resilient infrastructure, promote sustainable industrialization and foster innovation.

Variations

  • You could try animation by changing any of myBall's properties like you changed myBall.style.top. For example:
    • myBall.style.left: You can move the ball from left to right.
    • myBall.style.width: You can make the ball bigger, or smaller.
    • myBall.src: This may be the most interesting. You can actually change the picture. Just be sure to put all the image files in the same directory as the HTML page.
  • Can you think of how to make the ball look like a real bouncing ball, one that keeps bouncing up and down?
  • How about making it even more realistic, and have it lose some height with each bounce, and eventually stop?
  • For a multiple image animation, you could try animating a stick figure. From your ball animation you may have an idea how much an arm or leg should move with each time step, and what the time interval should be. Try it and see if the motion looks realistic!
  • For a fairly advanced animation, how about two stick figures bouncing the ball back and forth between them?
  • Another idea would be to try to relate your findings to the human visual system. What is the typical frame rate for displaying movies on a screen? How does this relate to the best timer intervals for your animation? Can you think of ways to measure visual response times? Persistence of vision? Computer monitor response times?

Careers

If you like this project, you might enjoy exploring these related careers:

Career Profile
If you've ever watched a cartoon, played a video game, or seen an animated movie, you've seen the work of multimedia artists and animators. People in these careers use computers to create the series of pictures that form the animated images or special effects seen in movies, television programs, and computer games. Read more
Career Profile
Computers are essential tools in the modern world, handling everything from traffic control, car welding, movie animation, shipping, aircraft design, and social networking to book publishing, business management, music mixing, health care, agriculture, and online shopping. Computer programmers are the people who write the instructions that tell computers what to do. Read more
Career Profile
Are you interested in how a website is set up and how the website runs? As a web developer and designer you could design a website's look and feel and create the code to make sure the website works. You could set up a website for your favorite store with payment options, making sure it works with the ever growing list of browsers and devices. Do you like working behind the scenes? You could design the layout or write the supporting code for an app or website while collaborating with other web… Read more

News Feed on This Topic

 
, ,

Cite This Page

General citation information is provided here. Be sure to check the formatting, including capitalization, for the method you are using and update your citation, as needed.

MLA Style

Science Buddies Staff. "Follow the Bouncing Ball: A Web Animation Project." Science Buddies, 14 July 2023, https://www.sciencebuddies.org/science-fair-projects/project-ideas/CompSci_p012/computer-science/follow-the-bouncing-ball-a-web-animation-project. Accessed 19 Mar. 2024.

APA Style

Science Buddies Staff. (2023, July 14). Follow the Bouncing Ball: A Web Animation Project. Retrieved from https://www.sciencebuddies.org/science-fair-projects/project-ideas/CompSci_p012/computer-science/follow-the-bouncing-ball-a-web-animation-project


Last edit date: 2023-07-14
Top
We use cookies and those of third party providers to deliver the best possible web experience and to compile statistics.
By continuing and using the site, including the landing page, you agree to our Privacy Policy and Terms of Use.
OK, got it
Free science fair projects.