deviceorientation and devicemotion

Edited JS from <a href="http://persistent.info/webkit/tools/sensors.html">This page</a>

by John Schulz

HTML

<h1>DeviceOrientation Sensors</h1>

CSS

body {
    margin: 0;
    padding: 5px;
    line-height: 0;
    font-size: 0;
}

h1 {
    position: absolute;
    bottom: 0;
    right: 0;
    margin: 0;
    padding: 5px;
    background: #eee;
    border-top: solid 1px #ccc;
    border-left: solid 1px #ccc;
    -webkit-border-radius: 10px 0 0 0;
    -moz-border-radius: 10px 0 0 0;
    border-radius: 10px 0 0 0;
    font: 20px Helvetica;
    font-weight: bold;
    color: #999;
}

canvas {
    border: solid 1px #eee;
    margin: 5px;
}

/* On the iPhone 4, have the graphs use 1 screen pixel per canvas pixel */
@media only screen and (-webkit-min-device-pixel-ratio: 2) {
body {
    padding: 2px;
}

canvas {
    width: 150px;
    height: 100px;
    margin: 2px;
}

h1 {
    font-size: 12px;
    padding: 2px;
}
}

JavaScript

var buffers = {};
var graphs = {};
var GRAPH_WIDTH = 300;
var GRAPH_HEIGHT = 200;

addEventListener('devicemotion', onDeviceMotion, false);
addEventListener('deviceorientation', onDeviceOrientation, false);
addEventListener('mousemove', onMouseMove, false);

function round(value) {
    return Math.round(value * 100) / 100;
}

function plot(value, id) {

    if (!buffers[id]) {
        buffers[id] = [];
        var canvas = document.createElement('canvas');
        canvas.width = GRAPH_WIDTH;
        canvas.height = GRAPH_HEIGHT;
        document.body.appendChild(canvas);

        var context = canvas.getContext('2d');
        context.lineWidth = 1.0;
        context.font = '12px Helvetica';
        context.strokeStyle = '#000';
        graphs[id] = context;
    }

    var buffer = buffers[id];
    var graph = graphs[id];

    buffer.push(value);
    if (buffer.length == GRAPH_WIDTH) {
        buffer.shift();
    }

    graph.clearRect(0, 0, GRAPH_WIDTH, GRAPH_HEIGHT);
    graph.textAlign = 'end';
    graph.fillStyle = '#aaa';
    graph.fillText(id, GRAPH_WIDTH - 2, 12);

    console.log('buffer', buffer.length);
    if (!buffer.length) {
        return;
    }

    var min = Number.MAX_VALUE;
    var max = -Number.MAX_VALUE;

    for (var i = 0; i < buffer.length; i++) {
        var value = buffer[i];
        if (value < min) min = value;
        if (value > max) max = value;
    }

    graph.beginPath();
    var scale = GRAPH_HEIGHT / (max - min);
    for (var i = 0; i < buffer.length; i++) {
        var value = buffer[buffer.length - 1 - i];
        var x = GRAPH_WIDTH - i;
        var y = GRAPH_HEIGHT - (value - min) * scale;
        if (i == 0) {
            graph.moveTo(x, y);
        } else {
            graph.lineTo(x, y);
        }
    }
    graph.stroke();

    graph.textAlign = 'start';
    graph.fillStyle = '#666';
    graph.fillText(round(min), 2, GRAPH_HEIGHT - 2);
    graph.fillText(round(max), 2, 10);
}

function onDeviceMotion(event) {
   ...