Animate2 Example -- Source Code

HTML Page -- index.htm

<!DOCTYPE html>

<!-- Animate2 Example
Source code file: styles.css
Move a square along a circle 
within the container -->

<html lang="en">
    <head>
        <title>Animation2 Example</title>
        <script src="script.js"></script>
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
        <h2>Animation2 Example</h2>

        <!-- Click button to run the animation. -->
        <p><button id="btn">
            Run Animation</button>
        </p>

        <!-- When button is clicked, the 
             square moves along a circle 
             within the container. -->
        <div id ="container">
            <div id ="square"></div>
        </div>
    </body>
</html>

CSS Page -- styles.css

 /* Animate2 Example
   Source code file: styles.css
   Move a square along a circle
   within the container */

#container {
    width: 400px;
    height: 400px;
    position: relative;
    background: yellow;
}

#square {
    width: 50px;
    height: 50px;
    left: 275px;
    top: 175px;
    position: absolute;
    background-color: red;
}

Script Page -- script.js

 // Animate2 Example
// Source code file: styles.css
// Move a square along a circle 
// within the container.

var timer = null;
function moveSquare() {
    var elem = document.getElementById("square"); 
    var t = 0;

    clearInterval(timer);
    timer = setInterval(frame, 5);

    function frame( ) {
        if (t >= 1.0) {
            clearInterval(timer);
        } 
        else {
            t += 0.01;
            angle = t * 2 * Math.PI;
            posx = 175.0 + 100.0 * Math.cos(angle);
            posy = 175.0 + 100.0 * Math.sin(angle);
            elem.style.left = posx + "px"; 
            elem.style.top = posy + "px"; 
        }
    }
}

function init( ) {
    var button = document.getElementById("btn");
    button.addEventListener("click", moveSquare);
}

window.addEventListener("load", init);