html5实现摇一摇换背景图功能(web开发)

时间:14-11-12 栏目:html5/css3 作者:zongyan86 评论:0 点击: 5,328 次

html5提供了devicemotion事件来实现重力感应的功能。下面来看下面的一个摇一摇切换婚纱的小游戏。

摇一摇婚纱

演示地址

http://www.kuaipao8.com/wedding/yaoyiyao.htm 

请用手机打开实验


代码如下

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width,initial-scale=1.0" />
    <title>手机摇一摇看我们的婚纱照!</title>
    <script type="text/javascript">
        Array.prototype.in_array = function (e) {
            for (i = 0; i < this.length; i++) {
                if (this[i] == e)
                    return true;
            }
            return false;
        }  

        var color = [];
        for (var i = 1; i < 38; i++) {
            color.push(i);
        }
        var temp = [];  
        var count = 0;
        if (window.DeviceMotionEvent) {
            var speed = 25;
            var x = y = z = lastX = lastY = lastZ = 0;
            window.addEventListener('devicemotion', function () {
                var acceleration = event.accelerationIncludingGravity;
                x = acceleration.x;
                y = acceleration.y;
                if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed) {
                    var rad = color[Math.round(Math.random() * 10) % 37];
                    if (temp.length == 37) {
                        alert("恭喜您,通过您的不懈努力,摇到了37张婚纱照。您的意志力,大家都惊呆了!在这里祝福您,已婚的幸福美满,单身的早日脱单!");
                    }
                    if (temp.in_array(rad)) {
                        document.getElementById("msg").innerHTML = "恭喜你摇到一张重复的婚纱照!已经摇到" + temp.length + "张婚纱照,不能放弃哦!摇到37张有惊喜哦!";
                    } else {
                        temp.push(rad);
                        count++;
                        document.getElementById("img").setAttribute("src", "http://www.kuaipao8.com/wedding/images/" + rad + ".jpg");
                        document.getElementById("msg").innerHTML = "恭喜你摇到第" + count + "张婚纱照!";
                    }
                }
                lastX = x;
                lastY = y;
            }, false);

        }  </script>
</head>
<body>
    一共37张照片,看看您能摇到多少张不一样的? <span id="msg" style="color: Red;"></span>  <a href="http://www.kuaipao8.com/wedding" title="摇累了?">摇累了?</a>
    <img id="img" />
</body>
</html>

web开发分享



声明: 本文由( zongyan86 )原创编译,转载请保留链接: html5实现摇一摇换背景图功能(web开发)

关注我们