This article describes how to use DeviceOrientation to implement the shake function in HTML5. For more information, see the important feature of HTML5: DeviceOrientation, it encapsulates the underlying direction and motion sensors in advanced mode, which 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 p # hand on the page, which is used to hold a hand shake image, and p # result is used to display the result information after shaking.
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.