Accelerometer
It was only a little while ago that I realized you could access the iPhone’s accelerometer through JavaScript. Which is kind of embarrassing since it’s been available since iOS 4.2. Anyhow, it’s really pretty simple, so here’s the crash course. There are two ways to go about using accelerometer data: devicemotion and deviceorientation.
Devicemotion
This is straight-up accelerometer data. Values are in m/s².
window.addEventListener("devicemotion", function(ev) { ev.acceleration; ev.accelerationIncludingGravity; }, false);
Acceleration and accelerationIncludingGravity each have three values (x, y, z) which pretty much do just what they sound like. For a device at rest, lying flat on a table, acceleration will return x:0, y:0, z:0, while accelerationIncludingGravity will return x:0, y:0, z:-9.8 (does that number sound familiar?). These values are pretty jittery, so you’ll probably want to smooth them out.
I built a demo that rotates an element based on devicemotion data: try it out on an iOS device.
Deviceorientation
This is simply how the device believes it’s positioned. Values are in degrees from 0 to 359.99…
window.addEventListener("deviceorientation", function(ev) { ev.beta; // x ev.gamma; // y ev.alpha; // z }, false);
Implementing smoothing here will be more tricky because when a value goes from 359 to 0, your smoothing function will want to spin the value back around to 0. Fortunately, these values seem to be much smoother than the pure acceleration numbers, so I just did without additional smoothing.
Rotation around the device’s z-axis (the direction you’re facing) will be set to 0 when the page loads, and it will also reset to 0 whenever you scroll the page, change browser tabs, or anything like that. So if you need a consistent direction, you should take a look at webkitCompassHeading.
And here’s a demo that uses deviceorientation.
Both demos show the accelerometer values, so you can get a feel for how they work with each method. Note that in both cases I’m swapping the X and Y values behind the scenes, based on the current screen orientation.
And just in case you really want to have a motion-rotated element on a page, I made a little script that’ll do it for you. Check it out.
These APIs work really well, so I want to see you do something really cool with them!