当前位置: 移动技术网 > IT编程>网页制作>Html5 > 基于html5 DeviceOrientation 实现微信摇一摇功能

基于html5 DeviceOrientation 实现微信摇一摇功能

2019年07月25日  | 移动技术网IT编程  | 我要评论

在html5中,deviceorientation特性所提供的devicemotion事件封装了设备的运动传感器时间,通过改时间可以获取设备的运动状态、加速度等数据(另还有deviceorientation事件提供了设备角度、朝向等信息)。

而通过devicemotion对设备运动状态的判断,则可以帮助我们在网页上就实现“摇一摇”的交互效果。

运动事件监听


复制代码
代码如下:

if (window.devicemotionevent) {
window.addeventlistener('devicemotion', devicemotionhandler, false);
} else {
alert('你的手机太差了,买个新的吧。');
}

获取加速度信息

“摇一摇”的动作既“一定时间内设备了一定距离”,因此通过监听上一步获取到的x, y, z 值在一定时间范围内的变化率,即可进行设备是否有进行晃动的判断。而为了防止正常移动的误判,需要给该变化率设置一个合适的临界值。


复制代码
代码如下:

function devicemotionhandler(eventdata) {
var acceleration = eventdata.accelerationincludinggravity;
var curtime = new date().gettime();
if ((curtime - last_update) > 100) {
var difftime = curtime - last_update;
last_update = curtime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = math.abs(x + y + z - last_x - last_y - last_z) / difftime * 10000;
var status = document.getelementbyid("status");
if (speed > shake_threshold) {
doresult();
}
last_x = x;
last_y = y;
last_z = z;
}
}

效果如图所示:


如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网