DeviceMotionEvent事件介绍

快乐打工仔 分类:实例代码

本章节介绍一下html5中的DeviceMotionEvent事件,需要的朋友可以做一下参考。

事件介绍:

(1).deviceorientation提供设备的物理方向信息,表示为一系列本地坐标系的旋角。

(2).devicemotion提供设备的加速信息,表示为定义在设备上的坐标系中的卡尔迪坐标。其还提供了设备在坐标系中的自转速率。若可行的话,事件应该提供设备重心处的加速信息。

(3).compassneedscalibration 用于通知Web站点使用罗盘信息校准上述事件。

用法简介:

注册一个deviceorientation事件的接收器:

window.addEventListener("deviceorientation", function (event) {
  // 处理event.alpha、event.beta及event.gamma
}, true);

将设备放置在水平表面,屏幕顶端指向西方,则其方向信息如下:

{
  alpha: 90,
   beta: 0,
   gamma: 0
};

为了获得罗盘指向,可以简单的使用360度减去alpha。若设被平行于水平表面,其罗盘指向为(360 - alpha)。 若用户手持设备,屏幕处于一个垂直平面且屏幕顶端指向上方。beta的值为90,alpha和gamma无关。 用户手持设备,面向alpha角度,屏幕处于一个垂直屏幕,屏幕顶端指向右方,则其方向信息如下:

{
  alpha: 270 - alpha,
  beta: 0,
  gamma: 90
};

只用自定义界面通知用户校准罗盘:

window.addEventListener("compassneedscalibration", function (event) {
  alert('您的罗盘需要校准,请将设备沿数字8方向移动。');
  event.preventDefault();
}, true);

注册一个devicemotion时间的接收器:

window.addEventListener("devicemotion", function (event) {
  // 处理event.acceleration、event.accelerationIncludingGravity、
  // event.rotationRate和event.interval
}, true);

将设备放置在水平表面,屏幕向上,acceleration为零,则其accelerationIncludingGravity信息如下:

{
  x: 0,
  y: 0,
  z: 9.81
};

设备做自由落体,屏幕水平向上,accelerationIncludingGravity为零,则其acceleration信息如下:

{
  x: 0,
  y: 0,
  z: -9.81
};

将设备安置于车辆至上,屏幕处于一个垂直平面,顶端向上,面向车辆后部。车辆行驶速度为v,向右侧进行半径为r的转弯。设备记录acceleration和accelerationIncludingGravity在位置x处的情况,同时设备还会记录rotationRate.gamma的负值:

{
  acceleration: {x: v^2/r, y:0, z:0},
  accelerationIncludingGravity: {x: v^2/r, y:0, z:9.81},
  rotationRate: {alpha: 0, beta: 0, gamma:-v/r*180/pi} 
};

应用实例:

if (window.DeviceMotionEvent) {
  window.addEventListener('devicemotion', deviceMotionHandler, false);
}
var speed = 30;//speed
var x = y = z = lastX = lastY = lastZ = 0;
function deviceMotionHandler(eventData) {
  var acceleration = eventData.accelerationIncludingGravity;
  x = acceleration.x;
  y = acceleration.y;
  z = acceleration.z;
  if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed || Math.abs(z - lastZ) > speed) {
    //简单的摇一摇触发代码
    alert(1);
  }
  lastX = x;
  lastY = y;
  lastZ = z;
}

回复

共1条回复 我来回复
  • chenzhanhong9
    chenzhanhong9
    这个人很懒,什么都没有留下~
    评论

    问一下为什么我if (window.DeviceMotionEvent) 这个事件然后npm run serve运行项目在http://localhost:8080/里有的 在http://192.168.1.141:8080/里就是undefined呢

    2年前 0条评论