码迷,mamicode.com
首页 > 移动开发 > 详细

H5实现的手机摇一摇

时间:2017-08-04 14:26:45      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:为什么   device   list   install   注意   计算   cti   containe   color   

原文:http://www.open-open.com/code/view/1430809715273

 

 

 <!DOCTYPE html>  
    <html lang="en">  
        <head>  
            <meta charset="utf-8">  
        </head>  
        <body>  
            <div id="status"></div>     
        </body>  
        <script>  
           var shake=4000,   
               last_update=0,   
               count=0,  
               x=y=z=last_x=last_y=last_z=0;  
           if(window.DeviceMotionEvent){  
                window.addEventListener("devicemotion",deviceMotionHandler,false);  
           }else{  
             alert("本设备不支持devicemotion事件");  
           }  
           console.log(new Date().valueOf());  
           function deviceMotionHandler(eventData){  
                var acceleration = eventData.accelerationIncludingGravity,  
                    currTime=new Date().valueOf(),  
                    diffTime=currTime-last_update;  
      
                    if(diffTime>100){  
                       last_update=currTime;  
                       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){  
                             count++;  
                             status.innerHTML = "你摇了中"+count+"" ;  
                       }  
                       last_x = x;  
                       last_y = y;  
                       last_z = z;  
                    }  
           }  
        </script>  
    </html>  

 

 

devicemotion 获取设备加速度信息。其事件对象返回有3个值,但是我用到的是accelerationIncludingGravity 考虑了重力的影响。地球引力值是9.81 返回的X,Y,Z 其中的Z轴就是9.81 不过有正负之分 水平向上在安卓里面显示的是是+9.81 在苹果里面显示的是-9.81 (最然对于我们的计算没有影响,但是写出来让大家了解一下,免得测试的时候有疑问)。

注意:返回的X,Y,Z的属性值的单位是m/s^2

acceleration
这个属性是没有考虑到重力影响的,很奇怪,我也在想为什么出两个标准。这个难道是考虑在真空吗。。。。

OK,来说说我们的代码。

设置了阀值4000(就是当加速度达到了这个值的时候,就触发了摇一摇的程序)。

获取上一次的时间last_update.

设置一个count来告诉大家你摇动了几次。

初始化各个轴的加速读,以及上一次的加速last_X,last_Y,last_Z.

如果设备支持DeviceMotionEvent就给window进行事件绑定。

获取当前时间currTime。

获取当前事件对象的accelerationIncludingGravity属性。

每100毫秒进行一次获取和判断加速度 X,Y,Z。

求的某一次的加速speed是否达到了阀值4000.

如果达到了就出发摇一摇事件。

最后再把这次的X,Y,Z的速度值复制给last_x,y,z.

真个代码的解析就是这样了。

 
 
 
speed=Math.abs(x+y+z-last_x-last_y-last_z)/diffTime*10000 为什么是乘以10000而不是1000
 
 

H5实现的手机摇一摇

标签:为什么   device   list   install   注意   计算   cti   containe   color   

原文地址:http://www.cnblogs.com/shihaiming/p/7284793.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!