Webkit ball

Uses webkit requestAnimationFrame and webkit deviceorientation event

by wellcaffeinated

HTML

<div class="physics"></div>
<p>Grab to move<br/>Press keyboard to bounce<br/>Now pick up your computer and tilt it!!!</p>

CSS

html,body {overflow: hidden;height: 100%;}
.physics {position: absolute; background: red; width: 100px; height: 100px; border-radius: 100px;}

JavaScript

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

function monitorDeviceOrientation(callback){
    if ( window.DeviceOrientationEvent ) {
            
            // Listen for the deviceorientation event and handle the raw data
            window.addEventListener( 'deviceorientation', function( eventData ) {
                
                var data = {
                    lr: eventData.gamma, // gamma is the left-to-right tilt in degrees, where right is positive
                    fb: eventData.beta, // beta is the front-to-back tilt in degrees, where front is positive
                    dir: eventData.alpha, // alpha is the compass direction the device is facing in degrees
                    grav: null
                };
                
                callback( data );
                
            }, false);
            
        } else if ( window.OrientationEvent ) {
            
            window.addEventListener('MozOrientation', function( eventData ) {
                
                var data = {
                    lr: eventData.x * 90, // x is the left-to-right tilt from -1 to +1, so we need to convert to degrees
                    fb: eventData.y * -90, // y is the front-to-back tilt from -1 to +1, so we need to convert to degrees
                                // We also need to invert the value so tilting the device towards us (forward) 
                                // results in a positive value. 
                    dir: null, 
                    grav: eventData.z // z is the vertical acceleration of the device
                };
                
                callback( data );
                
            }, false);
        }
}

$.fn.physics = function(physicalParams)...