刚刚过去的一年里基于微信的h5营销可谓是十分火爆,通过转发朋友圈带来的病毒式传播效果相信大家都不太陌生吧,刚好最近农历新年将至,我就拿一个“摇签”的小例子来谈一谈html5中如何调用手机重力感应的接口
演示代码:摇一摇,万福签
什么是重力感应 说到重力感应有一个东西不得不提,那就是就是陀螺仪,陀螺仪就是内部有一个陀螺,陀螺仪一旦开始旋转,由于轮子的角动量,陀螺仪有抗拒方向改变的特性,它的轴由于陀螺效应始终与初始方向平行,这样就可以通过与初始方向的偏差计算出实际方向。
手机中的方位轴
在web应用中调用手机陀螺仪接口
//摇一摇(使用deviceorientation事件, 本质是计算偏转角)//测试中发现有些设备不支持if(window.deviceorientationevent){ $(window).on('deviceorientation', function(e) { if (isstarted) { return true; } if (!lastacc) { lastacc = e; return true; } var dela = math.abs(e.alpha - lastacc.alpha); var delb = math.abs(e.beta - lastacc.beta); var delg = math.abs(e.gamma - lastacc.gamma); if ( (dela > 15 && delb > 15) || (dela > 15 && delg > 15) || (delb > 15 || delg > 15)) { start(); } lastacc = e; });
//摇一摇(使用devicemotion事件, 推荐,应为可以计算加速度)if(window.devicemotionevent) { var speed = 25; var x, y, z, lastx, lasty, lastz; x = y = z = lastx = lasty = lastz = 0; window.addeventlistener('devicemotion', function(event){ var acceleration = event.accelerationincludinggravity; x = acceleration.x; y = acceleration.y; if(math.abs(x-lastx) > speed || math.abs(y-lasty) > speed) { start(); } lastx = x; lasty = y; }, false);}
摇一摇的代码判断逻辑 var isstarted = false;// 开始摇签function start() { isstarted = true; $('.qiancover').hide(); $('.decode').hide(); $('.result').show(); // settimeout(showdecode, 3000);}// 显示正在解签function showdecode() { $('.result').hide(); $('.decode').show(); settimeout(jumptodecode, 3000);}// 跳至签文页面function jumptodecode(){ var urls = [#, #]; var jumpto = urls[parseint(math.random() * urls.length)]; window.location = jumpto;};
示例代码: https://github.com/lionrock/html5-example/tree/master/wechat-divination
参考文档: deviceorientation event specification