Archive for category html5/css3

Accessing accelerometer data with HTML5

I really like the concept of mobile web applications, i.e. applications that are meant to be run within the browser of mobile devices. I like this idea because I don’t fancy making the same application multiple times using different coding environments for each platform (iOS, Android, Blackberry etc.). Writing applications in HTML5, CSS3 and javascript can be a way to write a single application that can run on different platforms.

Yesterday, I wondered if a web application can access accelerometer data, i.e. the rotation of the phone relative to the ground. With some Googling if found this blog:

And indeed, I wrote a small script and verified that it is very easy to access accelerometer data. At least when your are using an iPhone4 and I’m not sure about other iPhone versions or Android.

Now I needed a quick way to do something with this data and I thought of using the accelerometer as a 3D remote control. Not very original, but a nice challenge.

Another google-search led to an article by Paul Hayes.

This brilliant blog describes how you can do 3D transformations using CSS3. Paul Hayes’ demo let’s you rotate the cube using the keyboard and touch gestures.

I wondered if I could add accelerometer control to it as well. And, indeed, using a few lines of code this was possible.

window.ondevicemotion = function(event) {
var xVal = event.accelerationIncludingGravity.x;
var yVal = event.accelerationIncludingGravity.y;

viewport.move({x: viewport.x - yVal});
viewport.move({y: viewport.y - xVal});

The result works on iPhone4. I have no ideas if it works on other devices as well. Unfortunately, if you rotate the phone to much, the view changes between portrait and landscape mode.
View it here.