H5摇一摇

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>摇一摇你的手机</div>
<script>
let SHAKE_SPEED_THRESHOLD = 300; //摇动速度阈值
let lastTime = 0;
let x = y = z = lastX = lastY = lastZ = 0;

function motionHandler(evt) {
let acceleration = evt.accelerationIncludingGravity;
let curTime = new Date();
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_THRESHOLD) {
alert("你摇动了手机")
}

lastX = x;
lastY = y;
lastZ = z;
}
}

if (window.DeviceMotionEvent) {
window.addEventListener("devicemotion", motionHandler, false)
} else {
alert("你的手机不支持位置感应")
}
</script>
</body>
</html>
posted @ 2019-04-24 15:22  逸_风  阅读(192)  评论(0编辑  收藏  举报