結合HTML5、CSS3、JS模擬微信搖一搖開發小記打賞

客戶想要通過網頁實現一個類似微信搖一搖的小游戲,周末在家沒事,就做了下,搖一搖之前有做,但是效果不是類似微信那樣的,所以照搬舊實現方案,采用github上人氣略高的一個Device Accelerometer封裝函數,這樣就不用自己去爬各種坑了。

搖動事件是解決了,但想模擬聲音、震動之類的,還得找一下新的api,因為之前沒用過,所以大概收集了下資料,下面簡單記錄一下。

搖動就不再贅述了,簡單幾步,可以參考這里https://github.com/alexgibson/shake.js

var myShakeEvent = new Shake({

threshold: 15, // optional shake strength threshold

timeout: 1000 // optional, determines the frequency of event generation

});

myShakeEvent.start();

window.addEventListener('shake', shakeEventDidOccur, false);

//function to call when shake occurs

function shakeEventDidOccur () {

//put your own code here etc.

alert('shake!');

}

聲音也簡單,之前一直沒用過HTML5新加的音視頻接口,今天剛好試了試,還挺好用,加以下兩個標簽,默認不加任何諸如autoplay之類的屬性,然后給個id,程序里通過id找到當前對象,調用play即可播放一次。

<audio id="run" src="js/shake_sound_male.mp3"></audio>
<audio id="match" src="js/shake_match.mp3"></audio>

再說震動,加以下判斷,如果支持就調用震動,傳入震動頻率時長即可,不過實測后發現微信里面不支持,所以這項功能只有在微信外其他瀏覽器中才能得以體現。

navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;

下面附上整段HTML、CSS與JS代碼,實現了css3過渡效果的滑動與JS滑動,也有打算使用CSS3 animation寫,用animationEnd事件增加回調,但由于之前寫搶紅包游戲時發現騰訊出品的大部分內嵌瀏覽器不支持animationEnd回調事件,就忽略了此項,簡單寫了下,勿拍磚哈

HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <meta name="msapplication-tap-highlight" content="no" />
    <title>搖一搖</title>
    <script src="js/shake.js"></script>
</head>
<body>
<div class="back">
    <div class="f">小紅花</div>
</div>
<div id="fore" class="fore"></div>
<div class="move-wrap">
    <div id="up" class="up animate-up" style="display: none;"></div>
    <div id="down" class="down animate-down" style="display: none;"></div>
</div>
<audio id="run" src="js/shake_sound_male.mp3"></audio>
<audio id="match" src="js/shake_match.mp3"></audio>
</body>
</html>

CSS部分

* { margin: 0; padding: 0; box-sizing: border-box;}
        html,body { height: 100%;}
        .fore { background: url("images/shake.jpg") no-repeat center; background-size: 100% 100%; position: absolute; z-index: 3; width: 100%; height: 100%;}

        .move-wrap { width: 100%; height: 100%; overflow: hidden; position: relative;}
        .up { background: url("images/shake.jpg") no-repeat center top; background-size: 100% 200%; position: absolute; z-index: 3; width: 100%; height: 50%; top:0;}
        .down { background: url("images/shake.jpg") no-repeat center bottom; background-size: 100% 200%; position: absolute; z-index: 3; width: 100%; height: 50%; bottom: 0;}

        .animate-up {
            transition: top 1.5s linear;
            -webkit-transition: top 1.5s linear;
        }
        .animate-down {
            transition: bottom 1.5s linear;
            -webkit-transition: bottom 1.5s linear;
        }

        .back { background: #666; position: absolute; z-index: 1;width: 100%; height: 100%; color: #FFF;}
        .f { height: 22px; position: relative; top:50%; width: 100%; text-align: center; margin-top: -11px;}

JS部分

var shake = new Shake({
        threshold: 15,
        timeout: 1000
    }),
    run = document.getElementById('run'),
    match = document.getElementById('match'),
    fore = document.getElementById('fore'),
    up = document.getElementById('up'),
    down = document.getElementById('down');

    shake.start();

    var vibrate = function(){
        navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
        if (navigator.vibrate) {
            navigator.vibrate([500, 100, 100, 100, 500, 100, 100, 100, 500, 100, 100, 100,0]);
        }
    };

    var supportCss3 = function(style) {
        var prefix = ['webkit', 'Moz', 'ms', 'o'],
                i,
                humpString = [],
                htmlStyle = document.documentElement.style,
                _toHumb = function (string) {
                    return string.replace(/-(\w)/g, function ($0, $1) {
                        return $1.toUpperCase();
                    });
                };

        for (i in prefix)
            humpString.push(_toHumb(prefix[i] + '-' + style));

        humpString.push(_toHumb(style));

        for (i in humpString)
            if (humpString[i] in htmlStyle) return true;

        return false;
    };

    var ShakeAnimate = function(support){
        var begin = function(){
            fore.style.display='none';
            up.style.display='block';
            down.style.display='block';
        };

        var end = function(){
            if(!support&amp;&amp;isEnd) return ;
            isEnd =1;
            upStep = - upStep;
            downStep = - downStep;
            fore.style.display='block';
            up.style.top = '0px';
            up.style.display='none';
            down.style.bottom='0px';
            down.style.display='none';
            match.play();
            vibrate();
        };
        if(support){
            this.animate = function(){
                begin();
                setTimeout(function(){
                    up.style.top='-100px';
                    down.style.bottom='-100px';
                    setTimeout(function(){
                        up.style.top='0px';
                        down.style.bottom='0px';
                        setTimeout(function(){
                            end();
                            match.play();
                        },1500);
                    },2500);
                },0);
            };
        }else{
            var isEnd = 0;

            var openingSpeed = 8;
            var openedDelay = 2000;

            var moveMax = -100;

            var upStep = 1;
            var downStep = 1;

            var isUpBack = 0;
            var isDownBack = 0;

            var moveUp = function(){
                var top = parseFloat(up.style.top)||0;
                if(isUpBack&amp;&amp;top&gt;=0) {
                    end();
                    return;
                }
                up.style.top=top-upStep + 'px';
                if(isUpBack||top&gt;moveMax){
                    setTimeout(moveUp,openingSpeed);
                }else{
                    isUpBack = 1;
                    upStep = - upStep;
                    setTimeout(moveUp,openedDelay);
                }
            };

            var moveDown = function(){
                var bottom = parseFloat(down.style.bottom)||0;
                if(isDownBack&amp;&amp;bottom&gt;=0) {
                    end();
                    return ;
                }
                down.style.bottom=bottom-downStep + 'px';
                if(isDownBack||bottom&gt;moveMax){
                    setTimeout(moveDown,openingSpeed);
                }else{
                    isDownBack =1;
                    downStep = - downStep;
                    setTimeout(moveDown,openedDelay);
                }
            };

            this.animate = function(){
                isEnd = 0;
                isUpBack = 0;
                isDownBack = 0;
                begin();
                moveUp();
                moveDown();
            };
        }
    };

    var ani = new ShakeAnimate(supportCss3('transition'));

    window.addEventListener('shake', shakeEventDidOccur, false);

    function shakeEventDidOccur() {
        run.play();
        ani.animate();
    }

發現博客代碼顯示還是問題很大,一直沒時間整個可以完美顯示代碼的主題,也不想再裝插件,所以,還是直接去github上看吧,地址https://github.com/veryto/html5_shake

結合HTML5、CSS3、JS模擬微信搖一搖開發小記
文章《結合HTML5、CSS3、JS模擬微信搖一搖開發小記》二維碼
  • 微信打賞
  • 支付寶打賞

已有4條評論

  1. 絕緣墊

    來露個臉

    2015-12-11 11:01 回復
  2. 劉興祥

    這代碼比較繁瑣的寧波PDM

    2015-11-04 12:44 回復

(必填)

(必填)

(可選)

黑龙江22选5开奖