Heim  >  Artikel  >  Web-Frontend  >  HTML5中如何调用手机重力感应的接口

HTML5中如何调用手机重力感应的接口

WBOY
WBOYOriginal
2016-05-17 09:07:052595Durchsuche

  刚刚过去的一年里基于微信的H5营销可谓是十分火爆,通过转发朋友圈带来的病毒式传播效果相信大家都不太陌生吧,刚好最近农历新年将至,我就拿一个“摇签”的小例子来谈一谈HTML5中如何调用手机重力感应的接口。

 

  演示代码:摇一摇,万福签

 

  什么是重力感应

 

  说到重力感应有一个东西不得不提,那就是就是陀螺仪,陀螺仪就是内部有一个陀螺,陀螺仪一旦开始旋转,由于轮子的角动量,陀螺仪有抗拒方向改变的特性,它的轴由于陀螺效应始终与初始方向平行,这样就可以通过与初始方向的偏差计算出实际方向。

 

HTML5中如何调用手机重力感应的接口

HTML5中如何调用手机重力感应的接口

HTML5中如何调用手机重力感应的接口

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);
}<br>

 

  摇一摇的代码判断逻辑

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

 

   来源:http://xunli.xyz/2016/01/12/html5-device-shake/?utm_source=tuicool&utm_medium=referral

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn