如何通过html5实现摇一摇的功能


本文摘自PHP中文网,作者jacklove,侵删。

原理:使用DeviceMotion实现,关于DeviceMotion介绍可以查看
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion

通过DeviceMotionEvent,可以获得accelerationIncludingGravity的x,y,z属性,根据x,y,z属性的变化来判断设备是否有摇一摇的事件发生。

accelerationIncludeingGravity说明:
The acceleration of the device. This value includes the effect of gravity, and may be the only value available on devices that don’t have a gyroscope to allow them to properly remove gravity from the data.

代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>

 <head>

  <meta http-equiv="content-type" content="text/html;charset=utf-8">   

  <title> html5使用DeviceMotionEvent实现摇一摇 </title>

  <style type="text/css">

  .center{position:absolute; width:640px; height:480px; left:50%; top:50%; margin-left:-320px; margin-top:-240px; line-height:480px; text-align:center; font-size:100px; }

  .normal{background:#000000;}

  .normal .txt{color:#FFFFFF;}

  .doing{background:#FF0000;}

  .doing .txt{color:#FFFF00;}

  </style>

 </head>

 <body id="mybody" class="normal">

    <p id="txt" class="txt center">请执行摇一摇</p>

 </body>

 <script type="text/javascript">

    var doing = 0;  // 判断是否在动画显示中

    var speed = 23; // 定义摇动的速度数值

    var lastx = 0;    var lasty = 0;    var lastz = 0;    function handleMotionEvent(event) {

        var x = event.accelerationIncludingGravity.x;        var y = event.accelerationIncludingGravity.y;        var z = event.accelerationIncludingGravity.z;        if(doing==0){            if(Math.abs(x-lastx)>speed || Math.abs(y-lasty)>speed){

                doing = 1;

                show();

            }

        }

        lastx = x;

        lasty = y;

        lastz = z;

    }    function show(){

        document.getElementById('mybody').className = 'doing';

        document.getElementById('txt').innerHTML = '执行了摇一摇';

        setTimeout(function(){

            doing=0;

            document.getElementById('mybody').className='normal';

            document.getElementById('txt').innerHTML = '请执行摇一摇';

        },3000);

    }

    window.addEventListener("devicemotion", handleMotionEvent, true); </script></html>

本文介绍了通过html5实现摇一摇的功能,更多相关内容请关注php中文网。

相关推荐:

如何通过MySql查看与修改auto_increment的方法

如何通过php生成网页桌面的快捷方式

利用js遍历获取表格内数据的方法

以上就是如何通过html5实现摇一摇的功能的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

HTML5 canvas图像处理的实现代码分享

HTML5新特性之移动设备api

HTML5多线程javascript解决方案web worker-专用worker和共享worker的详细代码介绍

h5的拖放应该如何实现

HTML5新增加的标签和表单新增属性的代码实例

HTML5几种在客户端存储数据的实例详解

h5怎样调用相机拍照并压缩图片

h5中的弹窗无法用webview弹出怎么解决

HTML5 canvas中如何绘制图像

如何解决HTML5微信播放全屏问题

更多相关阅读请进入《HTML5》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...