Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use DeviceOrientation of html5 to realize Wechat Shake function

Shulou Source: shulou.com Published: 2022-06-01 06:56:43 10月22日 Update

The knowledge of this article "how to use html5's DeviceOrientation to achieve Wechat shake function" is not understood by most people, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "how to use html5's DeviceOrientation to achieve Wechat shake function" article.

In HTML5, the DeviceMotion event provided by the DeviceOrientation feature encapsulates the motion sensor time of the device, and the data such as motion state and acceleration of the device can be obtained by changing the time (and the deviceOrientation event provides information such as device angle, orientation, etc.).

Through the judgment of the moving state of the equipment by DeviceMotion, it can help us to achieve the interactive effect of "shaking" on the web page.

Sports event monitoring

Copy the code

The code is as follows:

If (window.DeviceMotionEvent) {

Window.addEventListener ('devicemotion', deviceMotionHandler, false)

} else {

Alert ('your phone is too bad, buy a new one.')

}

Get acceleration information

The action of "shaking" is that the equipment has a certain distance in a certain period of time, so by monitoring the change rate of the x, y, z values obtained in the previous step in a certain time range, we can judge whether the equipment is shaking or not. In order to prevent the miscalculation of normal movement, it is necessary to set an appropriate critical value for the rate of change.

Copy the 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 above is about "how to use html5 DeviceOrientation to achieve Wechat shake function" this article content, I believe we all have a certain understanding, I hope the editor to share the content to help you, if you want to know more related knowledge content, please follow the industry information channel.

Tags: Device content code time motion function event information acceleration rate of change article status knowledge article change help monitoring appropriate threshold value Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB Apple OPPO Reno Microsoft Shulou Technology