Deviceorientation includes two events:
1, Deviceorientation: Packaging directional sensor data events, you can get the mobile phone static state of the direction of data, such as the mobile phone's angle, location, orientation and so on.
2, Devicemotion: Encapsulation of the motion sensor data events, can get mobile phone movement in the State of motion acceleration and other data.
Html
There is a div#hand on the page, used to place a hand-cranked picture, div#result to show the results of the shaking information.
<div id= "Hand" class= "Hand hand-animate" ></div>
<div id= "Result" ></div>
We can use CSS3 to enhance the effect of the page, using-webkit-animation animation effect to achieve the dynamic effect of the hand-cranked picture, please download the source code view.
Javascript
"Shake" This action is "a certain amount of time equipment at a certain distance", so through the devicemotion monitoring device shaking to get the value of x, Y, Z axis in a certain time range rate of change, that is to determine whether the device is shaking. In order to prevent the normal movement of the misjudgment, we need to set a suitable threshold for the change rate.
HTML5 to judge the device shaking code we use the already encapsulated Shake.js, project address:
Https://github.com/alexgibson/shake.js.
<script src= "Shake.js" ></script>
First instantiate the shake, then start listening device movement, monitoring equipment movement, callback monitoring results: Shakeeventdidoccur.
Window.onload = function () {
var myshakeevent = new Shake ({
Threshold:15
});
Myshakeevent.start ();
Window.addeventlistener (' Shake ', shakeeventdidoccur, false);
function Shakeeventdidoccur () {
var result = document.getElementById ("result");
Result.classname = "Result";
var arr = [' Sister one ', ' welfare picture set ', ' Code Agriculture Notes ', ' tyrants Gold '];
var num = Math.floor (math.random () *4);
result.innerhtml = "Congratulations, shake" +arr[num]+ "! ";
settimeout (function () {
Result.classname = "Result Result-show";
}, 1000);
}
};
Here, the function shakeeventdidoccur () can be customized, this example is to return the shaking results to the page displayed