Http://www.helloweba.com/view-blog-287.html
The HTML5 has an important feature: Deviceorientation, which has advanced encapsulation of the underlying direction and motion sensor, makes it easy to implement interesting functions such as gravity sensing, compass, etc. This article will combine with examples to introduce the use of HTML5 gravity motion and direction sensor to achieve mobile phone shake effect.
Deviceorientation consists of two events:
1, Deviceorientation: Encapsulate the direction sensor data events, you can get the mobile phone in the static state of the direction of data, such as the angle of the mobile phone, orientation, orientation and so on.
2, Devicemotion: The event that encapsulates the motion sensor data, can get the motion acceleration of the mobile phone.
Html
There is a div#hand on the page that is used to place a hand-cranked picture, Div#result used to show the information of the result after shaking.
<div id="hand" class="hand hand-animate"></div>
<div id="result"></div>
We can use CSS3 to enhance the page effect, using the-webkit-animation animation effect to achieve the dynamic effect of hand-cranked pictures, please download the source code to view.
Javascript
"Shake" This action is "a certain amount of time within a certain distance", so through the Devicemotion monitoring device sloshing obtained by the x, Y, Z axis value in a certain time range of the rate of change, that is, to determine whether the device is shaking. In order to prevent the normal movement of the false, we need to set a suitable threshold for the rate of change.
HTML5 Judging the device sloshing code we use the already encapsulated Shake.js, project address: Https://github.com/alexgibson/shake.js.
http://www.helloweba.com/view-blog-287.html<script src="shake.js"></script>
First instantiate the shake, then start listening device movement, monitoring device movement, callback monitoring results: Shakeeventdidoccur.
Window.onload =function (){
var myshakeevent =New Shake ({
Threshold15
});
Myshakeevent.start ();
Window.addeventlistener (' Shake ', shakeeventdidoccur, false);
function Shakeeventdidoccur (){
var result = document.getElementById ("Result");
Result.classname ="Result";
var arr = [' A sister ',' Welfare picture set ',' Yard notes a book ',' Local tyrants Gold a set '];
var num = Math.floor (math.random () *4);
result.innerhtml = "Congratulations, shake the +arr[num]+"! ";
SetTimeout (function (){
Result.classname = "Result result-show";
}, 1000);
}
};
HTML5 mobile phone gravity and direction sensing application--shake shake effect