Parallaxing Parallax on iOS

GitHub has a bit of a friendly competition complex. When Corey Johnson released URL Hunter, there was a lot of talk about how that minigame could be topped. Cameron McEfee, the famed designer behind all of the parallax effects on GitHub’s site (the 404 page, the 500 page, the about page, and so on) took Corey’s URL bar game and parallaxed it. In doing all of this parallax work, Cameron open sourced his parallax plugin for jQuery itself: plax.

Parallax is a perspective-based animation technique: move your mouse and you simulate moving your frame of reference around. Cameron’s plax only worked based on mouse movement, though:

…which means all of these gorgeous animations of this handsome fellow didn’t work on your favorite iOS device. What a bummer. So I parallaxed his parallax and added support for the accelerometer and gyroscope present in iPhones and iPads, which Apple generously gave us access to in the iOS 4.3 release last year.

So now we can do cool things to GitHub’s Cloud:

Safari’s Accelerometer Support

It’s really pretty easy to add this to your own apps and libraries. Apple exposes the accelerometer to us through DeviceMotionEvent, a class that handles “signification change in motion”. (You might also want to take a look at DeviceOrientationEvent, too.) The change to plax is pretty straightforward, but it’s really just a matter of handling the ondevicemotion event and grabbing the values from that motion:

window.ondevicemotion = function(e) {
  x = e.rotationRate.beta
  y = e.rotationRate.alpha
}

In this case, rotationRate is the rate of rotation, which is a bit more relevant for parallax. You can also grab rotationRate.gamma, which is the rotation positive out of the screen on the z axis. Unfortunately rotationRate is for those devices with gyroscopes: in other words, iPhone 4 and above. Once we have the rotation rate pulled from the phone we can pipe that information into plax and plax handles the coordination of layers based on that.

Depending on your use case, you also might want to take a look at accelerationIncludingGravity, which gives you a measurement of the acceleration of the movement happening on the device.

Todo

This at least gives us some real-world parallax support on iOS, which is great. There’s some improvements that could be made to retaining rotation position in parallax (which would give it more of a realistic feel), and there’s oodles of accelerometers in Android phones and in laptops, too. If you’re looking for a fun hack day, you might want to build in support for those devices (or create a library abstraction for movement in JavaScript!) and send us a pull request.

Vus : 1040
Publié par Nicolas Paris : 149