Implementation of wechat shake-a-shake function based on HTML5 deviceorientation

Time:2021-11-26

In HTML5, the devicemotion event provided by the deviceorientation feature encapsulates the motion sensor time of the device. By changing the time, the motion state, acceleration and other data of the device can be obtained (in addition, the deviceorientation event provides the angle, orientation and other information of the device).

The judgment of device motion state through devicemotion can help us realize the interactive effect of “shaking” on the web page.

Sports event monitoring

Copy code

The code is as follows:

if (window.DeviceMotionEvent) {
window.addEventListener(‘devicemotion’, deviceMotionHandler, false);
} else {
Alert (‘your mobile phone is terrible, buy a new one ‘);
}

Get acceleration information

The “shake” action means that “the equipment has a certain distance within a certain time”. Therefore, judge whether the equipment shakes by monitoring the change rate of X, y and Z values obtained in the previous step within a certain time range. In order to prevent misjudgment of normal movement, it is necessary to set an appropriate critical value for the change rate.

Copy code

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 * 10000;
var status = document.getElementById(“status”);
if (speed > SHAKE_THRESHOLD) {
doResult();
}
last_x = x;
last_y = y;
last_z = z;
}
}

The effect is shown in the figure:

Recommended Today

Vue、Three. JS implementation panorama

1、 First, we need to create a Vue project This paper mainly records the process of building panorama in detail, so building Vue project is not described too much. 2、 Install three js npm install three –save npm install three-trackballcontrols –save npm install three-orbit-controls –save npm i three-obj-mtl-loader –save npm i three-fbx-loader –save npm i […]