Use the HTML5 devicemotion event to give your mobile phone a shake lottery, annual lottery, and html5devicemotion
Shake JS script logic:
The next step is the implementation of JS script logic on the mobile end. The implementation of shaking requires the use of the newly added devicemotion event in html5 to obtain information about the device's speed change in position and direction, the basic usage of this event is as follows:
If (window. DeviceMotionEvent) {window. addEventListener ('devicemotion', handler ,! 1); lastTime = new Date ();} else {alert ('your browser does not support the shake function .');}
The devicemotion event object has an accelerationIncludingGravity attribute, which includes an object that contains the x, y, and z attributes. Considering the natural gravity acceleration of the z axis, it tells you the acceleration in each direction. For details about how to use this API, refer to the relevant information on the Internet. The specific logic is as follows:
Function handler (e) {var current = e. accelerationIncludingGravity; var currentTime; var timeDifference; var deltaX = 0; var deltaY = 0; var deltaZ = 0; // record the last time the device was on x, y, acceleration in the z direction if (lastX = null) & (lastY = null) & (lati = null) {lastX = current. x; lastY = current. y; lastZ = current. z; return;} // get the absolute acceleration gap between the two moving directions. deltaX = Math. abs (lastX-current. x); deltaY = Math. abs (lastY-current. y); deltaZ = Math. abs (lastZ-current. z); // when the gap is greater than the set threshold value and the interval is greater than the specified threshold value, the logic if (deltaX> threshold) is triggered) & (deltaY> threshold) | (deltaX> threshold) & (deltaZ> threshold) | (deltaY> threshold) & (deltaZ> threshold) {currentTime = new Date; timeDifference = currentTime. getTime ()-lastTime. getTime (); // time interval if (timeDifference> timeout) {// trigger the shake event dealShake (); lastTime = new Date ;}} lastX = current. x; lastY = current. y; lastZ = current. z ;}
Do not consider the question of the probability of winning each other's prizes
Complete code example:
1 <! DOCTYPE html> 2