HTML5 uses DeviceOrientation to implement the shake function. html5orientation
HTML5 has an important feature: DeviceOrientation, which encapsulates the underlying direction and motion sensors in advanced mode. It enables us to easily implement interesting functions such as gravity sensing and compass. This article will introduce how to use HTML5 gravity motion and orientation sensors to shake mobile phones.
DeviceOrientation includes two events:
1. deviceOrientation: encapsulates the event of the direction sensor data to obtain the direction data in the mobile phone's static state, such as the angle, orientation, and orientation of the mobile phone.
2. deviceMotion: events that encapsulate motion sensor data can be used to obtain Motion Acceleration and other data in the mobile phone's motion status.
HTML
There is a div # hand on the page, which is used to hold a hand shake image. div # result is used to display the result information after shaking.
<div id="hand" class="hand hand-animate"></div> <div id="result"></div>
We can use CSS3 to enhance the page effect, and use the-webkit-animation effect to achieve the dynamic effect of the hand image. For details, please download the source code to view.
Javascript
The "Shake" action is "the device has been in a certain distance for a certain period of time". Therefore, the devicemotion listens to the x, y, the change rate of the Z axis value within a certain period of time, that is, to determine whether the device is shaking. To prevent misjudgment of normal movement, a critical value must be set for the change rate.
In HTML5, we use the encapsulated shake. js code to determine device shaking. The project address is https://github.com/alexgibson/shake.js.
<script src="shake.js"></script>
First, instantiate Shake and start to listen to the device movement, listen to the device movement, and call back the listening result: 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 = ['one sister, one sister, one Welfare picture set, one farmer's note, and one tuhao gold set]; var num = Math. floor (Math. random () * 4); result. innerHTML = "congratulations, shake it" + arr [num] + "! "; SetTimeout (function () {result. className =" result-show ";}, 1000 );}};
Here, the shakeEventDidOccur () function can be customized. In this example, the result of shaking is displayed on the page. See the DEMO.
The above is all the content of this article. I hope you will like it.