Home > Web Front-end > H5 Tutorial > Implement WeChat shake function based on html5 DeviceOrientation_html5 tutorial skills

Implement WeChat shake function based on html5 DeviceOrientation_html5 tutorial skills

WBOY
Release: 2016-05-16 15:46:30
Original
1921 people have browsed it

In HTML5, the DeviceMotion event provided by the DeviceOrientation feature encapsulates the device's motion sensor time. By changing the time, you can obtain the device's motion status, acceleration and other data (there is also a deviceOrientation event that provides device angle, orientation and other information) .

Determining the motion status of the device through DeviceMotion can help us achieve the "shake" interactive effect on the web page.

Motion event monitoring


Copy code
The code is as follows:

if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
alert('Your phone is terrible, buy a new one.');
}

Get acceleration information

The "shake" action means that the device moves a certain distance within a certain period of time. Therefore, by monitoring the change rate of the x, y, z values ​​obtained in the previous step within a certain time range, you can determine whether the device has Make a shaking judgment. In order to prevent misjudgment of normal movement, an appropriate critical value needs to be set for the rate of change.


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 as shown in the picture:


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template