KinectJS and physics

Based on http://www.html5canvastutorials.com/labs/html5-canvas-physics-engine-with-curve-detection/

HTML

<!DOCTYPE HTML>
<html>
    <head>
        <script src="https://raw.githubusercontent.com/ericdrowell/KineticJS/master/kinetic.js"></script>
    </head>
    <body onmousedown="return false;">
        <div id="container">
        </div>
    </body>
</html>

CSS

body {
    margin: 0px;
    padding: 0px;
}

canvas {
    border: 1px solid #9C9898;
}

JavaScript

/*
 * Vector math functions
 */

function dot(a, b) {
    return ((a.x * b.x) + (a.y * b.y));
}

function magnitude(a) {
    return Math.sqrt((a.x * a.x) + (a.y * a.y));
}

function normalize(a) {
    var mag = magnitude(a);

    if (mag == 0) {
        return {
            x: 0,
            y: 0
        };
    }
    else {
        return {
            x: a.x / mag,
            y: a.y / mag
        };
    }
}

function add(a, b) {
    return {
        x: a.x + b.x,
        y: a.y + b.y
    };
}

function angleBetween(a, b) {
    return Math.acos(dot(a, b) / (magnitude(a) * magnitude(b)));
}

function rotate(a, angle) {
    var ca = Math.cos(angle);
    var sa = Math.sin(angle);
    var rx = a.x * ca - a.y * sa;
    var ry = a.x * sa + a.y * ca;
    return {
        x: rx * -1,
        y: ry * -1
    };
}

function invert(a) {
    return {
        x: a.x * -1,
        y: a.y * -1
    };
}

/*
 * this cross product function has been simplified by
 * setting x and y to zero because vectors a and b
 * lie in the canvas plane
 */

function cross(a, b) {
    return {
        x: 0,
        y: 0,
        z: (a.x * b.y) - (b.x * a.y)
    };
}

function animate(ball, curve, frame) {
    var ballLayer = ball.getLayer();

    // update ball
    updateBall(ball, curve, frame);

    // draw
    ballLayer.draw();
}



function getNormal(curve, ball, frame) {
    var curveLayer = curve.getLayer();
    var context = curveLayer.getContext();
    var testRadius = 20; // pixels
    var totalX = 0;
    var totalY = 0;

/*
 * check various points around the center point
 * to determine the normal vector
 */

    for (var n = 0; n < 20; n++) {
        var angle = n * 2 * Math.PI / 20;
        var offsetX = testRadius * Math.cos(angle);
        var offsetY = testRadius * Math.sin(angle);
        var testX = ball.x + offsetX;
        var testY = ball.y + offsetY;
        if (!context.isPointInPath(testX, testY)) {
            totalX += offsetX;
            totalY += offsetY;
        }
  ...