HTML5模拟微信“摇一摇” [前端开发]

用HTML5的window对象的DeviceMotionEvent事件,可以模拟实现微信“摇一摇”的功能。

演示环境:


主要代码:
<script type="text/javascript">
        var SHAKE_THRESHOLD = 2500;
        var last_update = 0;
        var x = y = z = last_x = last_y = last_z = 0;
        var processing = false;

        function init() {
            whir.loading.remove();
            if (window.DeviceMotionEvent) {
                window.addEventListener('devicemotion', deviceMotionHandler, false);
            } else {
                alert('not support mobile event');
            }
        }

        function deviceMotionHandler(eventData) {
            var acceleration = eventData.accelerationIncludingGravity;
            var curTime = new Date().getTime();
            if ((curTime - last_update) > 100) {
                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) {
                    if (!processing) {
                        //防止多次摇动
                        processing = true; 
                        //播放音乐
                        var media = document.getElementById("musicBox");
                        media.play();

                        //延时响应,等摇晃音乐播放了再处理业务逻辑
                        setTimeout("if (confirm('您摇动了设备,继续“摇一摇”吗?')) {processing = false;}", 1000);
                    }
                }
                last_x = x;
                last_y = y;
                last_z = z;
            }
        }
        window.onload = function () {
            init();
        };

    </script>
    <audio style="display: none" id="musicBox" preload="metadata" src="yaoyiyao.mp3"> 
    </audio>