移动端陀螺仪【又叫角速度传感器】,

<html>
    
    <head>
        <title>DeviceOrientationEvent</title>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
        <script src="js/jquery-3.1.1.min.js"></script>
        <script src="js/eventutil.js"></script>
    </head>
    
    <body>
        <div id="arrow"></div>
    </body>

</html>
<script>
    try {
        var text = "";
        window.addEventListener("deviceorientation", orientationHandler, false);
        function orientationHandler(event) {
            text = ""
            var arrow = document.getElementById("arrow");
            text += "左右旋转:rotate alpha{" + Math.round(event.alpha) + "deg)<p>";
            text += "前后旋转:rotate beta{" + Math.round(event.beta) + "deg)<p>";
            text += "扭转设备:rotate gamma{" + Math.round(event.gamma) + "deg)<p>";
            arrow.innerHTML = text;
        }
    } catch(e) {
        $("#arrow").html(e.message)
    }
</script>


eventutil.js代码如下:
var EventUtil = new Object;
EventUtil.formatEvent = function (oEvent) {
     //isIE和isWin引用到一个js文件,判断浏览器和操作系统类型
     if (isIE && isWin) {
         oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
         //IE只支持冒泡,不支持捕获
         oEvent.eventPhase = 2;
         oEvent.isChar = (oEvent.charCode > 0);
         oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
         oEvent.pageY = oEvent.clientY + document.body.scrollTop;
         //阻止事件的默认行为
         oEvent.preventDefault = function () {
             this.returnValue = false;
         };
          //将toElement,fromElement转化为标准的relatedTarget
         if (oEvent.type == "mouseout") {
             oEvent.relatedTarget = oEvent.toElement;
         } else if (oEvent.type == "mouseover") {
             oEvent.relatedTarget = oEvent.fromElement;
         }
         //取消冒泡     
         oEvent.stopPropagation = function () {
             this.cancelBubble = true;
         };
         oEvent.target = oEvent.srcElement;
         //添加事件发生时间属性,IE没有
         oEvent.time = (new Date).getTime();
     }
     return oEvent;
};
EventUtil.getEvent = function() {
     if (window.event) {
         //格式化IE的事件
         return this.formatEvent(window.event);
     } else {
         return EventUtil.getEvent.caller.arguments[0];
     }
};

 

 

 

示例角度转变图:

 

 

 

posted @ 2017-05-05 11:08  苏尘尘  阅读(661)  评论(0编辑  收藏  举报