Js Ball gravity and air drag

by schrodingers

HTML

<canvas id="canvas" height="400" width="500">Get a better browser!</canvas>

CSS

canvas {
                display:block;
                margin:20px auto;
                background: #34495e;
                border:1px solid #34495e;
                height:400px;
                width:500px;
            }

JavaScript

/* Burak Kanber */
var width = 500;
var height = 400;
var canvas = ctx = false;
var frameRate = 1/40; // Seconds
var frameDelay = frameRate * 1000; // ms
var loopTimer = false;
var flat = ["#2ecc71", "#e74c3c", "#3498db", "#9b59b6", "#f1c40f", "#e67e22", "#be643c", "#ecf0f1", "#1abc9c", "#2c3e50", "#f5f5f5", "#bdc3c7", "#7f8c8d", "#95a5a6", "#e0e0e0", "#34495e"];
/*
 * Experiment with values of mass, radius, restitution,
 * gravity (ag), and density (rho)!
 * 
 * Changing the constants literally changes the environment
 * the ball is in. 
 * 
 * Some settings to try:
 * the moon: ag = 1.6
 * water: rho = 1000, mass 5
 * beach ball: mass 0.05, radius 30
 * lead ball: mass 10, restitution -0.05
 */
var ball = {
    position: {x: width/2, y: 0},
    velocity: {x: 10, y: 0},
    mass: 0.1, //kg
    radius: 15, // 1px = 1cm
    restitution: -0.7
    };

var Cd = 0.47;  // Dimensionless
var rho = 1.22; // kg / m^3
var A = Math.PI * ball.radius * ball.radius / (10000); // m^2
var ag = 9.81;  // m / s^2
var mouse = {x: 0, y: 0, isDown: false};

function getMousePosition(e) {
    mouse.x = e.pageX - canvas.offsetLeft;
    mouse.y = e.pageY - canvas.offsetTop;
}
var mouseDown = function(e) {
    if (e.which == 1) {
        getMousePosition(e);
        mouse.isDown = true;
        ball.position.x = mouse.x;
        ball.position.y = mouse.y;
    }
}
var mouseUp = function(e) { 
    if (e.which == 1) {
        mouse.isDown = false;
        ball.velocity.y = (ball.position.y - mouse.y) /10;
        ball.velocity.x = (ball.position.x - mouse.x) / 10;
    }
}

var setup = function() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    
    canvas.onmousemove = getMousePosition;
    canvas.onmousedown = mouseDown;
    canvas.onmouseup = mouseUp;
    ctx.fillStyle = flat[2];
        
    loopTimer = setInterval(loop, frameDelay);
}
var loop = function() {
    if ( ! mouse.isDown) {
        // Do physics
            // Drag force: Fd = -1/2 * Cd...