手机
当前位置:查字典教程网 >网页设计 >HTML5教程 >基于html5 DeviceOrientation 实现微信摇一摇功能
基于html5 DeviceOrientation 实现微信摇一摇功能
摘要:在HTML5中,DeviceOrientation特性所提供的DeviceMotion事件封装了设备的运动传感器时间,通过改时间可以获取设备...

在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;

}

}

效果如图所示:

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

【基于html5 DeviceOrientation 实现微信摇一摇功能】相关文章:

html5 worker 实例(一) 为什么测试不到效果

html5 canvas 简单画板实现代码

html5 css3网站菜单实现代码

基于html5实现的图片墙效果

Html5 FileReader实现即时上传图片功能实例代码

html5 button autofocus 属性介绍及应用

html5指南-4.使用Geolocation实现定位功能

基于html5 canvas实现漫天飞雪效果实例

html5指南-3.如何实现html元素拖拽功能

HTML5+lufylegend实现游戏中的卷轴

精品推荐
分类导航