Pendulum Clock

by cuzzea

HTML

<canvas id="canvas" height="600" width="400"></canvas>

CSS

canvas {
                display:block;
                margin:0px auto;
                height:600px;
                width:400px;
                border:none;
            }

JavaScript

var height = 600; var width = 400;
var canvas = ctx = false;
var frameRate = 1/40;
var frameDelay = frameRate * 1000;
var loopTimer = false;
var lastTime = false;

window.requestAnimFrame = (function(){
    return  window.requestAnimationFrame       || 
        window.webkitRequestAnimationFrame || 
        window.mozRequestAnimationFrame    || 
        window.oRequestAnimationFrame      || 
        window.msRequestAnimationFrame     || 
        function( callback ){
            window.setTimeout(callback, 1000 / 60);
        };
})();

var pendulum = {mass: 1, length:150, theta: 0 * Math.PI/180 , omega: 0, alpha:0, J:0};
var setup = function() {
    pendulum.J = pendulum.mass * pendulum.length * pendulum.length / 500;
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    
    ctx.strokeStyle = "black";
    ctx.fillStyle = "gold";
    
    // loopTimer = setInterval(loop, frameDelay);
    lastTime = new Date();
    requestAnimFrame(loop);
}
var loop = function(time) {
    var deltaT = (time - lastTime.getTime()) / 1000;

    /* 
    When switching away from the window, 
    requestAnimationFrame is paused. Switching back
    will give us a giant deltaT and cause an explosion.
    We make sure that the biggest possible deltaT is 50 ms
    */

    if (deltaT > 0.050)
    {
        deltaT = 0.050;
    }
    deltaT = 0.01;

    time = new Date(time);

    /* Velocity Verlet */
    /* Calculate current position from last frame's position, velocity, and acceleration */
    pendulum.theta += pendulum.omega * deltaT + ( 0.5 * pendulum.alpha * deltaT * deltaT );

    /* Calculate forces from current position. */
    var T = pendulum.mass * 9.81 * Math.cos(pendulum.theta) * pendulum.length;
	
    /* Current acceleration */
    var alpha = T / pendulum.J;

    /* Calculate current velocity from last frame's velocity and 
        average of last frame's acceleration with this frame's acceleration. */
    pendulum.omega += 0.5 * (alpha +...