Example 20 Using acceleration and rotation detection Below is an example on how to use acceleration and rotation detection. It makes use of the throttle function in the underscore library, which you can find at http://underscorejs.org/ to make sure the event handling function is only executed once every 1000 milliseconds.
NB: This example shows how one can capture the acceleration and rotation of a device. Possible uses would be to animate a sprite based on the motion of the device, creating a game-like element in a banner. window.ondevicemotion = function(event) { ax = event.accelerationIncludingGravity.x ay = event.accelerationIncludingGravity.y az = event.accelerationIncludingGravity.z rotation = event.rotationRate; if (rotation != null) { arAlpha = Math.round(rotation.alpha); arBeta = Math.round(rotation.beta); arGamma = Math.round(rotation.gamma); logAcceleration(ax, ay, az, arAlpha, arBeta, arGamma); } else { logAcceleration(ax, ay, az, 0, 0, 0); } }
logAcceleration = function(){
var i = 1;
return _.throttle(function(x, y, z, a, b, c){
if(i < 10) {
// your code here
// right now we’re just logging the results with a maximum of ten times
console.log("(" + x + ", " + y + ", " + z + "), (" + a + ", " + b + ", " + c + ")");
}
i = i + 1;
}, 1000);
}();
Example 21 Creating a panorama effect Below is an example on how to use the device orientation to create a panorama effect. To see a working demo, scan this
QR with your mobile device.
("DeviceOrientationEvent" in window)
? window.addEventListener('deviceorientation', deviceOrientationHandler, false)
: alert("Your browser does not support device orientation.");
// handler for device orientation event
function deviceOrientationHandler(e) {
// rotation along the x-axis
var alphaX = Math.floor(e.alpha);
// rotation along the y-axis
var betaY = Math.floor(e.beta);
// rotation along the z-axis
var gammaZ = Math.floor(e.gamma);
// adjusting the left property of the container div
// based on the rotation along the x-axis
$("#container").css({"left": (alphaX * (6693/1080))});
}
The image that has been used for the panorama view fits 3 times in the container div (320x240 px), to make sure that the image is visually correct at the left and right endpoints (repeat-x and overflow visible). To make sure that the image moves smoothly by using the alpha value, the left property is defined by: alpha * ((3*width image)/(3*360))
You can also move an image by using the y and z axis. See also here an explanation about orientation and motion data.
Comments
0 comments
Article is closed for comments.