How to realize the Shake function of Wechat through html5 DeviceOrientation
This article will explain in detail how to achieve Wechat shake function through html5 DeviceOrientation. The content of the article is of high quality, so the editor shares it for you as a reference. I hope you will have some understanding of the relevant knowledge after reading this 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
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.
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:
About how to achieve Wechat shake function through html5 DeviceOrientation to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.