The shake function is implemented based on html5 DeviceOrientation, and html5 performs shake-like operations.
Since it has been added for a long time and many of my friends are playing, how can I implement the shake Function Based on html5 DeviceOrientation? The following content is shared with you by the Helper's house for your reference.
In HTML5, The DeviceMotion event provided by the DeviceOrientation feature encapsulates the device's motion sensor time, you can change the time to obtain the device's motion status, acceleration, and other data (In addition, the deviceOrientation event provides the device angle, orientation, and other information ).
The DeviceMotion can be used to determine the movement status of the device, which helps us achieve the Interaction Effect of "Shake" on the webpage.
Sports event monitoring
The Code is as follows:
If (window. DeviceMotionEvent ){
Window. addEventListener ('deviceid', deviceMotionHandler, false );
} Else {
Alert ('your cell phone is too bad. Buy a new one. ');
}
Obtain acceleration information
The "Shake" action is "The device is a certain distance in a certain period of time". Therefore, you can listen to the change rate of the x, y, and z values obtained in the previous step within a certain period of time, to determine whether the device is shaking. To prevent misjudgment of normal movement, a critical value must be set for the change rate.
The Code is as follows:
Function deviceMotionHandler (eventData ){
Var acceleration = eventData. accelerationIncludingGravity;
Var curTime = new Date (). getTime ();
If (curTime-last_update)> 100 ){
Var diffTime = curTime-last_update;
Last_update = curTime;
X = acceleration. x;
Y = acceleration. y;
Z = acceleration. z;
Var speed = Math. abs (x + y + z-last_x-last_y-last_z)/diffTime x 10000;
Var status = document. getElementById ("status ");
If (speed> SHAKE_THRESHOLD ){
DoResult ();
}
Last_x = x;
Last_y = y;
Last_z = z;
}
}
Effect: