First, the principle:
Using Devicemotion to get the moving speed, the difference ratio of the device moving relative to the previous time
Two:
Third, the source code:
First determine if the device supports HTML5 shake function if (window. Devicemotionevent) {//Gets the movement speed, gets the difference of the device movement relative to the previous time than Window.addeventlistener (' devicemotion ', Devicemotionhandler, FALSE);} else{alert (' Hello, your current device does not seem to support gravity sensing Oh! ‘);} Set the threshold, this value can be set according to their own needs, the default is almost 3000. var shakethreshold = 3000;//Set the last update time to compare var lastupdate = 0;//Set position rate var Curshakex =curshakey=curshakez=lastshakex=lastshakey=lastshakez=0; function Devicemotionhandler (event) {//Get gravity accelerated var acceleration =event.accelerationincludinggravity; Get 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; Y-Axis acceleration curshakey = ACCELERATION.Y; Z-axis Acceleration Curshakez = acceleration.z; var speed = Math.Abs (Curshakex + curshakey + curshakez-lastshakex-lastshakey-lastshakez)/difftime * 10000; if (Speed > Shakethreshold) { TODO related methods, such as://Play sound shakeaudio.play (); Play the 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 sound var shakeaudio = new Audio (); SHAKEAUDIO.SRC = ' Sound/shake_sound.mp3 '; var shake_options = {preload: ' auto '}for (var key in shake_options) {if (s Hake_options.hasownproperty (Key) && (key in Shakeaudio)) {Shakeaudio[key] = Shake_options[key]; }}
Iv. Source code Download: Click to download
Transferred from: http://www.cnblogs.com/waitingbar/p/4682215.html
HTML5 The realization shakes a shake