Guest User

Untitled

a guest
Jan 18th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.30 KB | None | 0 0
  1. var shakeThreshold = 10000; // 定义一个摇动的阈值
  2. var lastUpdate = 0; // 记录上一次摇动的时间
  3. var x, y, z, lastX, lastY, lastZ; // 定义x、y、z记录三个轴的数据以及上一次触发的数据
  4.  
  5. // 监听传感器运动事件
  6. var shake = true;
  7. if (window.DeviceMotionEvent) {
  8. window.addEventListener('devicemotion', deviceMotionHandler, false);
  9. } else {
  10. shake = false;
  11. alert('您的设备不支持摇一摇');
  12. }
  13.  
  14. // 运动传感器处理
  15. function deviceMotionHandler(eventData) {
  16. if (!shake) {
  17. return false;
  18. }
  19. var acceleration = eventData.accelerationIncludingGravity; // 获取含重力的加速度
  20. var curTime = new Date().getTime();
  21.  
  22. // 100毫秒进行一次位置判断
  23. if ((curTime - lastUpdate) > 100) {
  24.  
  25. var diffTime = curTime - lastUpdate;
  26. lastUpdate = curTime;
  27. x = acceleration.x;
  28. y = acceleration.y;
  29. z = acceleration.z;
  30.  
  31. var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000;
  32. // 前后x, y, z间的差值的绝对值和时间比率超过了预设的阈值,则判断设备进行了摇晃操作
  33. if (speed > shakeThreshold) {
  34. doShake();
  35. }
  36.  
  37. lastX = x;
  38. lastY = y;
  39. lastZ = z;
  40. }
  41. }
  42.  
  43. function doShake() {
  44. alert(11111);
  45. }
Add Comment
Please, Sign In to add comment