天天看點

HTML5——監聽手機的一些事件:手機加速度devicemotion、裝置方向變化deviceorientation、手機搖一搖、指南針

1. devicemotion:監聽手機加速度變化的事件(比如:手機瘋狂搖擺)

屬性:均為隻讀屬性

(1)accelerationIncludingGravity:重力加速度(包括重心引力9.8)

(2)acceleration:加速度(需要裝置陀螺儀支援)

(3)rotationRate(alpha,beat,gamma);旋轉速度

(4)interval:擷取的時間間隔

搖一搖:

<!DOCTYPE html>
<html >

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>test</title>
    <style>
        #redPacket{
            position: absolute;
            left: 50%;
            top: 50%;
            width: 300px;
            height: 400px;
            /* border: 1px solid black; */
            margin-top: -200px;
            margin-left: -150px;
            opacity: 0;
        }
        #tip{
            color: red;
            font-size: 40px;
            opacity: 1;
        }
    </style>
</head>

<body>
    <div id="tip">搖一搖得紅包</div>
   <div id="redPacket"></div>
    <script>
      var SHAKE_THRESHOLD = 800;
      var last_update = 0;
      var x, y, z, last_x=0, last_y=0, last_z=0;
      function deviceMotionHeadler(eventData){
          var acceleration = eventData.accelerationIncludingGravity;
          var curTime = new Date().getTime();
          if((curTime - last_update) > 300){
              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;
              if(speed > SHAKE_THRESHOLD){
                  alert('恭喜你獲得紅包!');
                  var div = document.getElementById('redPacket');
                  var img = new Image();
                  img.src = 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3378701361,2399708000&fm=27&gp=0.jpg';
                  img.onload = function(){
                      div.appendChild(img);
                      img.style.width = '300px';
                      img.style.height = '400px';
                      tip.style.opacity = 0;
                      div.style.opacity = 1;
                  }
              }
              last_x = x;
              last_y = y;
              last_z = z;
          }
      }  
      window.addEventListener('devicemotion', deviceMotionHeadler, false);
    </script>
</body>

</html>
           

了解:手機抖動的時間要大于300ms,防止使用者拿手機時,突然抖動而觸發搖一搖功能;速度要大于800,證明使用者是在快速搖手機。 

2. deviceOrientation:監聽裝置在方向上的變化的事件

詳情:https://developer.mozilla.org/zh-CN/docs/Web/API/Detecting_device_orientation

屬性:

alpha:裝置沿z軸方向的選轉,水準面上的選擇,範圍:-360~360

beta:裝置沿x軸方向的旋轉,由前向後,範圍:-180~180

gamma:裝置沿y軸方向的旋轉,由左向右,範圍:-90~90

webkitCompassHeading:與正北方向的角度差,正北方向為0,正南方向:180;範圍:0~360;(安卓手機沒有該方法)

HTML5——監聽手機的一些事件:手機加速度devicemotion、裝置方向變化deviceorientation、手機搖一搖、指南針
<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <p>旋轉:<span id="alpha">0</span></p>
    <p>前後:<span id="beta">0</span></p>
    <p>扭轉:<span id="gamma">0</span></p>
    <p>方向:<span id="heading">0</span></p>

    <script>
    function DeviceOrientationHandler(event){
        var alpha = event.alpha,
            beta = event.beta,
            gamma = event.gamma,
            webkitCompassHeading = event.webkitCompassHeading;
        
        if(alpha != null || beta != null || gamma != null){
            
            //判斷螢幕方向
            var html = "";
            if( gamma > 0 ){
                html = "向右傾斜" + gamma;
            }else{
                html = "向左傾斜" + gamma;
            }
            document.getElementById("gamma").innerHTML = html;

            var str = '';
            if( beta > 0 ){
                str = "向前傾斜" + beta;
            }else{
                str = "向後傾斜" + beta;
            }

            var head = '';
            var headNum = Math.round(Math.round(webkitCompassHeading/45) + 7)%8;
            switch (headNum) {
                case 0:
                    head = '東北';
                    break;
                case 1:
                    head = '東';
                    break;
                case 2:
                    head = '東南';
                    break;
                case 3:
                    head = '南';
                    break;
                case 4:
                    head = '西南';
                    break;
                case 5:
                    head = '西';
                    break;
                case 6:
                    head = '西北';
                    break;
                case 7:
                    head = '北';
            }
            
            document.getElementById("beta").innerHTML = str;

            document.getElementById("alpha").innerHTML = alpha;

            document.getElementById('heading').innerHTML = head + '   ' + webkitCompassHeading;
   
        }else{
            document.body.innerHTML = "目前浏覽器不支援DeviceOrientation";
        }
    }
    if(window.DeviceOrientationEvent){
        window.addEventListener('deviceorientation',DeviceOrientationHandler, false);
    }else{
        alert("您的浏覽器不支援DeviceOrientation");
    }

    
    
    
    </script>
</body>
</html>
           
HTML5——監聽手機的一些事件:手機加速度devicemotion、裝置方向變化deviceorientation、手機搖一搖、指南針

指南針:

<!DOCTYPE html>
<html >
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
            list-style: none;
        }
        html{
            background: #333;
            color: #fff;
        }
        .box{
            position: relative;
            top: 100px;
            margin: 0 auto;
            width: 300px;
            height: 300px;
            /* border: 1px solid #fff; */
        }
        .pin{
            position: absolute;
            top: -50px;
            left: 50%;
            margin-left: -2px;
            width: 4px;
            height: 50px;
            background: #fff;
        }
        .ten{
            position: absolute;
            top: 50%;
            left: 50%;
            margin-left: -100px;
            margin-top: -100px;
            width: 200px;
            height: 200px;
        }
        .h, .l{
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
        }
        .ten .h{

            width: 2px;
            height: 200px;
            
        }
        .ten .l{
            width: 200px;
            height: 2px;
            
        }
        ul{
            width: 300px;
            height: 300px;
            border-radius: 50%;
            transition: all 10ms linear;
        }
        li{
            position: absolute;
            top: 0;
            left: 50%;
            margin-left: -1px;
            width: 2px;
            height: 20px;
            background: red;
            transform-origin: 1px 150px;
        }

        span{
            position: absolute;
            top: -20px;
            left: 50%;
            transform: translate(-50%, -50%);
            color: #fff;
        }   
    </style>
</head>
<body>
    
    <p>方向:<div id="heading">0</div></p> 

    <div class="box">
       <div class="pin"></div> 
       <div class="ten">
           <div class="l"></div>
           <div class="h"></div>
       </div>
       <ul>
           <li><span style="color:red">0</span></li>
           <li><span>330</span></li>
           <li><span>300</span></li>
           <li><span>270</span></li>
           <li><span>240</span></li>
           <li><span>210</span></li>
           <li><span>180</span></li>
           <li><span>150</span></li>
           <li><span>120</span></li>
           <li><span>90</span></li>
           <li><span>60</span></li>
           <li><span>30</span></li>
       </ul>
    </div>
    <script>
        function lineDraw() {
            var li = document.getElementsByTagName('li');
            var span = document.getElementsByTagName('span');
            var len = li.length;
            for(var i = 0; i < len; i++) {  
                // span[i].style.transform = 'rotate('+ -30 * i+'deg)';
                li[i].style.transform = 'rotate('+30*i+'deg)';
            }
        }
        lineDraw();

        function move(ang) {
            var ul = document.getElementsByTagName('ul')[0];
            ul.style.transform= 'rotate('+ang+'deg)';
        }

        function DeviceOrientationHandler(event){
            var webkitCompassHeading = event.webkitCompassHeading;
            // if(webkitCompassHeading != null){
                //判斷螢幕方向
                var head = '';
                var headNum = Math.round(Math.round(webkitCompassHeading/45) + 7)%8;
                switch (headNum) {
                    case 0:
                        head = '東北';
                        break;
                    case 1:
                        head = '東';
                        break;
                    case 2:
                        head = '東南';
                        break;
                    case 3:
                        head = '南';
                        break;
                    case 4:
                        head = '西南';
                        break;
                    case 5:
                        head = '西';
                        break;
                    case 6:
                        head = '西北';
                        break;
                    case 7:
                        head = '北';
                }
                move(webkitCompassHeading);
                
                document.getElementById('heading').innerHTML = head + '  ' + Math.round(webkitCompassHeading);
            // }else{
            //     document.body.innerHTML = "目前浏覽器不支援DeviceOrientation";
            // }
        }
        
    if(window.DeviceOrientationEvent){
        window.addEventListener('deviceorientation',DeviceOrientationHandler, false);
    }else{
        alert("您的浏覽器不支援DeviceOrientation");
    }   
    </script>
</body>
</html>
           
HTML5——監聽手機的一些事件:手機加速度devicemotion、裝置方向變化deviceorientation、手機搖一搖、指南針

繼續閱讀