<!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>motion(运动)</title>
</head>
<body>
<script>
var shakeThreshold = 1000; // 定义一个摇动的阈值
var lastUpdate = 0; // 记录上一次摇动的时间
var x, y, z, lastX, lastY, lastZ; // 定义x、y、z记录三个轴的数据以及上一次触发的数据
// 监听传感器运动事件
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
alert('本设备不支持devicemotion事件');
}
// 运动传感器处理
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity; // 获取含重力的加速度
var curTime = new Date().getTime(); // 100毫秒进行一次位置判断
if ((curTime - lastUpdate) > 100) {
var diffTime = curTime - lastUpdate;
lastUpdate = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - lastX - lastY - lastZ) / diffTime * 10000; // 前后x, y, z间的差值的绝对值和时间比率超过了预设的阈值,则判断设备进行了摇晃操作
if (speed > shakeThreshold) {
//doSomething
alert(11);
}
lastX = x;
lastY = y;
lastZ = z;
}
}
</script>
</body>
</html>
手机晃动监测
最新推荐文章于 2024-08-13 17:41:19 发布