方向事件deviceorientation
该事件实在设备方向发生变化时触发, 使用方法如下;
window.addeventlistener('deviceorientation', orientationhandler, true);
回调函数orientationhandler会接收到一个deviceorientationevent类型参数, 包含以下信息.
属性名 说明
absolute 如果方向数据跟地球坐标系和设备坐标系有差异, 则为true
alpha 设备在alpha方向上旋转的角度, 范围为0-360
beta 设备在beta方向上旋转的角度, 范围为-180-180
gamma 设备在gamma方向上旋转的角度, 范围为-90-90
移动事件devicemotion
该事件实在设备位置发生变化时触发
window.addeventlistener('devicemotion', motionhandler, false);
该回调函数会接受devicemotionevent类型参数, 包含以下信息.
属性名 说明
acceleration 设备在x,y,z三个轴的方向上移动的距离, 以抵消重力加速度
accelerationincludinggravity 设备在x,y,z三个轴方向移动的距离, 包含重力加速度
rotationrate 设备在alpha, beta, gamma三个方向旋转的角度
interval 从设备获取数据的频率, 单位是毫秒
代码部分
<!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>摇一摇</title> </head> <body> <p> 摇一摇 </p> <script> const shake_speed = 300; let lasttime = 0;//上次变化的时间 let x = y = z = lastx = lasty = lastz = 0;//位置变量初始化 function motionhandler(event) { let acceleration = event.accelerationincludinggravity; let curtime = date.now();//取得当前时间 if ((curtime - lasttime) > 120) { let difftime = curtime - lasttime; lasttime = curtime; x = acceleration.x; y = acceleration.y; z = acceleration.z; //计算摇动速度 let speed = math.abs(x + y + z - lastx - lasty - lastz) / difftime * 1000; if (speed > shake_speed) { alert("你摇动了手机"); } lastx = x; lasty = y; lastz = z; } } if(window.devicemotionevent) { window.addeventlistener('devicemotion', motionhandler, false); } else { alert("你的设备不支持位置感应"); } </script> </body> </html>
相信看了这些案例你已经掌握了方法,更多精彩请关注其它相关文章!
相关阅读:
html5中的dom编程的实现步骤
html里的事件怎么使用
用canvas做出时钟实现步骤
以上就是h5做出手机摇一摇功能的实现步骤的详细内容。
