QQ摇一摇

HTML5提供了访问传感器的API,分别是DeviceOrientationEvent和DeviceMotionEvent

实现方法:

监听devicemotion=>

设备在x,y,z方向上移动的距离和前一次移动的距离之差/两次事件的时间差即设备移动速度=>

与预速度(可通过多次测试取平均值)相比,如果大于之前的预设定值,则发生抖动

 

html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文档标题</title>
</head>
<body>
    <h1>Shake your phone</h1>
</body>
</html>

 

js

var shake_speed_threshold = 300;//摇动速度阈值
var lastTime = 0;//last change time
var x = y = z = lastX = lastY = lastZ;//x,y,z speed initialization
function motionHandler(event) {
    var acceleration = event.accelerationIncludingGravity;//取得包含重力加速的位置信息
    var curTime = Date.now();//get the current time
    if ((curTime - lastTime) > 120) {
        var diffTime = curTime - lastTime;//difference of the two times
        lastTime = curTime;//save the time
        x = acceleration.x;
        y = acceleration.y;
        z = acceleration.z;
        var speed = Math.abs(x + y + z - lastX - lasy - lastZ) / diffTime * 1000;//calulate the speed
        if (speed > shake_speed_threshold) {//judge the speed is over the pre_speed or not
            alert("You've shaken the phone!");
        }
        //save the positions
        lastX = x;
        lastY = y;
        lastZ = z;
    }
}
if (window.DeviceMotionEvent) {
    window.addEventListener('devicemotion', motionHandler, false);
} else {
    alert('Your device dose not support the position sensing.');
}

 

posted @ 2021-02-05 21:23  XXXSANS  阅读(129)  评论(0编辑  收藏  举报