HTML5 implements shake, HTML5 implements shake
I. Principle:
Use devicemotion to get the moving speed, and get the difference ratio between the device and the previous time.
Ii ,:
// First determine whether the device supports the HTML5 shake function if (window. deviceMotionEvent) {// get the moving speed, and obtain the difference value between the device and the previous time window. addEventListener ('devicdemo', deviceMotionHandler, false);} else {alert ('hello, your current device does not seem to support gravity sensing! ');} // Set the critical value. This value can be set based on your own needs. The default value is 3000, which is similar to var shakeThreshold = 3000. // set the last update time, used to compare var lastUpdate = 0; // set the location rate var curShakeX = curShakeY = curShakeZ = lastShakeX = lastShakeY = lastShakeZ = 0; function deviceMotionHandler (event) {// obtain the var acceleration = event for gravity acceleration. accelerationIncludingGravity; // obtain the current timestamp var curTime = new Date (). getTime (); if (curTime-lastUpdate)> 100) {// time difference var diffTime = curTime-lastUpdate; lastUpdate = curTime; // X axis acceleration curShakeX = acceleration. x; // acceleration of the Y axis curShakeY = acceleration. y; // acceleration of the Z axis curShakeZ = acceleration. z; var speed = Math. abs (curShakeX + curShakeY + curShakeZ-lastShakeX-lastShakeY-lastShakeZ)/diffTime * 10000; if (speed> latency) {// TODO related methods, such as: // playback effect shakeAudio. play (); // play an animation $ ('. shake_box '). addClass ('shake _ box_focus '); clearTimeout (shakeTimeout); var shakeTimeout = setTimeout (function () {$ ('. shake_box '). removeClass ('shake _ box_focus ') ;}, 1000)} lastShakeX = curShakeX; lastShakeY = curShakeY; lastShakeZ = curShakeZ ;}} // pre-shake the voice var shakeAudio = new Audio (); shakeAudio. src = 'sound/shake_soundout'; var shake_options = {preload: 'auto'} for (var key in shake_options) {if (shake_options.hasOwnProperty (key) & (key in shakeAudio )) {shakeAudio [key] = shake_options [key] ;}}
4. Download source code: Click to download
TIPS: optimization code can be proposed to share and make progress together...