H5頁面的九宮格解鎖

其他不說, 上代碼

(function() {
    window.H5lock = function(obj) {
        this.height = obj.height;
        this.width = obj.width;
        this.chooseType = Number(window.localStorage.getItem('chooseType')) || obj.chooseType;
    };

    function getDis(a, b) {
        return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
    };

    H5lock.prototype.pickPoints = function(fromPt, toPt) {
        var lineLength = getDis(fromPt, toPt);
        var dir = toPt.index > fromPt.index ? 1 : -1;

        var len = this.restPoint.length;
        var i = dir === 1 ? 0 : (len - 1);
        var limit = dir === 1 ? len: -1;

        while (i !== limit) {
            var pt = this.restPoint[i];

            if (getDis(pt, fromPt) + getDis(pt, toPt) === lineLength) {
                this.drawPoint(pt.x, pt.y);
                this.lastPoint.push(pt);
                this.restPoint.splice(i, 1);
                if (limit > 0) {
                    i--;
                    limit--;
                }
            }

            i += dir;
        }
    }

    H5lock.prototype.drawCle = function(x, y) { // 初始化解鎖密碼面板
        this.ctx.strokeStyle = '#CFE6FF';
        this.ctx.lineWidth = 2;
        this.ctx.beginPath();
        this.ctx.arc(x, y, this.r, 0, Math.PI * 2, true);
        this.ctx.closePath();
        this.ctx.stroke();
    }
    H5lock.prototype.drawPoint = function() { // 初始化圓心
        for (var i = 0; i < this.lastPoint.length; i++) {
            this.ctx.fillStyle = '#CFE6FF';
            this.ctx.beginPath();
            this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.fill();
        }
    }
    H5lock.prototype.drawStatusPoint = function(type) { // 初始化狀態(tài)線條
        for (var i = 0; i < this.lastPoint.length; i++) {
            this.ctx.strokeStyle = type;
            this.ctx.beginPath();
            this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r, 0, Math.PI * 2, true);
            this.ctx.closePath();
            this.ctx.stroke();
        }
    }
    H5lock.prototype.drawLine = function(po, lastPoint) { // 解鎖軌跡
        this.ctx.beginPath();
        this.ctx.lineWidth = 3;
        this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);
        console.log(this.lastPoint.length);
        for (var i = 1; i < this.lastPoint.length; i++) {
            this.ctx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
        }
        this.ctx.lineTo(po.x, po.y);
        this.ctx.stroke();
        this.ctx.closePath();

    }
    H5lock.prototype.createCircle = function() { // 創(chuàng)建解鎖點(diǎn)的坐標(biāo)锁施,根據(jù)canvas的大小來平均分配半徑
        var n = this.chooseType;
        var count = 0;
        this.r = this.ctx.canvas.width / (2 + 4 * n); // 公式計(jì)算
        this.lastPoint = [];
        this.arr = [];
        this.restPoint = [];
        var r = this.r;
        for (var i = 0; i < n; i++) {
            for (var j = 0; j < n; j++) {
                count++;
                var obj = {
                    x: j * 4 * r + 3 * r,
                    y: i * 4 * r + 3 * r,
                    index: count
                };
                this.arr.push(obj);
                this.restPoint.push(obj);
            }
        }
        this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
        for (var i = 0; i < this.arr.length; i++) {
            this.drawCle(this.arr[i].x, this.arr[i].y);
        }
        //return arr;
    }
    H5lock.prototype.getPosition = function(e) { // 獲取touch點(diǎn)相對(duì)于canvas的坐標(biāo)
        var rect = e.currentTarget.getBoundingClientRect();
        var po = {
            x: e.touches[0].clientX - rect.left,
            y: e.touches[0].clientY - rect.top
        };
        return po;
    }
    H5lock.prototype.update = function(po) { // 核心變換方法在touchmove時(shí)候調(diào)用
        this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);

        for (var i = 0; i < this.arr.length; i++) { // 每幀先把面板畫出來
            this.drawCle(this.arr[i].x, this.arr[i].y);
        }

        this.drawPoint(this.lastPoint); // 每幀花軌跡
        this.drawLine(po, this.lastPoint); // 每幀畫圓心
        for (var i = 0; i < this.restPoint.length; i++) {
            var pt = this.restPoint[i];

            if (Math.abs(po.x - pt.x) < this.r && Math.abs(po.y - pt.y) < this.r) {
                this.drawPoint(pt.x, pt.y);
                this.pickPoints(this.lastPoint[this.lastPoint.length - 1], pt);
                break;
            }
        }

    }
    H5lock.prototype.checkPass = function(psw1, psw2) { // 檢測(cè)密碼
        var p1 = '',
        p2 = '';
        for (var i = 0; i < psw1.length; i++) {
            p1 += psw1[i].index + psw1[i].index;
        }
        for (var i = 0; i < psw2.length; i++) {
            p2 += psw2[i].index + psw2[i].index;
        }
        return p1 === p2;
    }
    H5lock.prototype.storePass = function(psw) { // touchend結(jié)束之后對(duì)密碼和狀態(tài)的處理
        if (this.pswObj.step == 1) {
            if (this.checkPass(this.pswObj.fpassword, psw)) {
                this.pswObj.step = 2;
                this.pswObj.spassword = psw;
                document.getElementById('title').innerHTML = '密碼保存成功';
                this.drawStatusPoint('#2CFF26');
                window.localStorage.setItem('passwordxx', JSON.stringify(this.pswObj.spassword));
                window.localStorage.setItem('chooseType', this.chooseType);
            } else {
                document.getElementById('title').innerHTML = '兩次不一致肩狂,重新輸入';
                this.drawStatusPoint('red');
                delete this.pswObj.step;
            }
        } else if (this.pswObj.step == 2) {
            if (this.checkPass(this.pswObj.spassword, psw)) {
                document.getElementById('title').innerHTML = '解鎖成功';
                this.drawStatusPoint('#2CFF26');
            } else {
                this.drawStatusPoint('red');
                document.getElementById('title').innerHTML = '解鎖失敗';
            }
        } else {
            this.pswObj.step = 1;
            this.pswObj.fpassword = psw;
            document.getElementById('title').innerHTML = '再次輸入';
        }

    }
    H5lock.prototype.makeState = function() {
        if (this.pswObj.step == 2) {
            document.getElementById('updatePassword').style.display = 'block';
            //document.getElementById('chooseType').style.display = 'none';
            document.getElementById('title').innerHTML = '請(qǐng)解鎖';
        } else if (this.pswObj.step == 1) {
            //document.getElementById('chooseType').style.display = 'none';
            document.getElementById('updatePassword').style.display = 'none';
        } else {
            document.getElementById('updatePassword').style.display = 'none';
            //document.getElementById('chooseType').style.display = 'block';
        }
    }
    H5lock.prototype.setChooseType = function(type) {
        chooseType = type;
        init();
    }
    H5lock.prototype.updatePassword = function() {
        window.localStorage.removeItem('passwordxx');
        window.localStorage.removeItem('chooseType');
        this.pswObj = {};
        document.getElementById('title').innerHTML = '繪制解鎖圖案';
        this.reset();
    }
    H5lock.prototype.initDom = function() {
        var wrap = document.createElement('div');
        var str = '<h4 id="title" class="title">繪制解鎖圖案</h4>' + '<a id="updatePassword" style="position: absolute;right: 5px;top: 5px;color:#fff;font-size: 10px;display:none;">重置密碼</a>' + '<canvas id="canvas" width="300" height="300" style="background-color: #305066;display: inline-block;margin-top: 15px;"></canvas>';
        wrap.setAttribute('style', 'position: absolute;top:0;left:0;right:0;bottom:0;');
        wrap.innerHTML = str;
        document.body.appendChild(wrap);
    }
    H5lock.prototype.init = function() {
        this.initDom();
        this.pswObj = window.localStorage.getItem('passwordxx') ? {
            step: 2,
            spassword: JSON.parse(window.localStorage.getItem('passwordxx'))
        }: {};
        this.lastPoint = [];
        this.makeState();
        this.touchFlag = false;
        this.canvas = document.getElementById('canvas');
        this.ctx = this.canvas.getContext('2d');
        this.createCircle();
        this.bindEvent();
    }
    H5lock.prototype.reset = function() {
        this.makeState();
        this.createCircle();
    }
    H5lock.prototype.bindEvent = function() {
        var self = this;
        this.canvas.addEventListener("touchstart",
        function(e) {
            e.preventDefault(); // 某些android 的 touchmove不宜觸發(fā) 所以增加此行代碼
            var po = self.getPosition(e);
            console.log(po);
            for (var i = 0; i < self.arr.length; i++) {
                if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {

                    self.touchFlag = true;
                    self.drawPoint(self.arr[i].x, self.arr[i].y);
                    self.lastPoint.push(self.arr[i]);
                    self.restPoint.splice(i, 1);
                    break;
                }
            }
        },
        false);
        this.canvas.addEventListener("touchmove",
        function(e) {
            if (self.touchFlag) {
                self.update(self.getPosition(e));
            }
        },
        false);
        this.canvas.addEventListener("touchend",
        function(e) {
            if (self.touchFlag) {
                self.touchFlag = false;
                self.storePass(self.lastPoint);
                setTimeout(function() {

                    self.reset();
                },
                300);
            }

        },
        false);
        document.addEventListener('touchmove',
        function(e) {
            e.preventDefault();
        },
        false);
        document.getElementById('updatePassword').addEventListener('click',
        function() {
            self.updatePassword();
        });
    }
})();

怎么用呢?

< !DOCTYPE html > <html lang = "en" > <head > <meta charset = "UTF-8" > <meta name = "viewport"content = "width=device-width, initial-scale=1.0, user-scalable=no" > <title > H5lock < /title>
    <style type="text/css ">
        body {
            text-align: center;
            background-color: #305066;
        }
        .title {
            color: #22C3AA;
        }
    </style>
</head>
<body>
<script type="text / javascript " src="H5lock.js "></script>
<script type="text / javascript ">
    new H5lock({
        chooseType: 3
    }).init();
</script>
</body>
</html>"

測(cè)試地址(PS:只支持移動(dòng)端)

http://122.11.41.29/rzq/untitled2/index.html

實(shí)現(xiàn)方式指南

一個(gè)canvas標(biāo)簽搞定

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末栅螟,一起剝皮案震驚了整個(gè)濱河市篱竭,隨后出現(xiàn)的幾起案子掺逼,更是在濱河造成了極大的恐慌,老刑警劉巖吕喘,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件氯质,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡闻察,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門呢灶,熙熙樓的掌柜王于貴愁眉苦臉地迎上來鸯乃,“玉大人跋涣,你說我怎么就攤上這事『牝龋” “怎么了性置?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵揍堰,是天一觀的道長嗅义。 經(jīng)常有香客問我隐砸,道長,這世上最難降的妖魔是什么褪那? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任博敬,我火速辦了婚禮峰尝,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘武学。我一直安慰自己,他們只是感情好硼补,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布沛鸵。 她就那樣靜靜地躺著曲掰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪栏妖。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天宛裕,我揣著相機(jī)與錄音论泛,去河邊找鬼。 笑死岩榆,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的勇边。 我是一名探鬼主播粒褒,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼祥款!你這毒婦竟也來了月杉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤奠伪,失蹤者是張志新(化名)和其女友劉穎首懈,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體究履,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡最仑,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年泥彤,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片吟吝。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡剑逃,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出蛹磺,到底是詐尸還是另有隱情,我是刑警寧澤裙品,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布清酥,位于F島的核電站蕴侣,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏昆雀。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一揩懒、第九天 我趴在偏房一處隱蔽的房頂上張望挽封。 院中可真熱鬧,春花似錦智亮、人聲如沸点待。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽苗踪。三九已至,卻和暖如春通铲,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背央串。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國打工碗啄, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人饲宿。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓,卻偏偏與公主長得像仗阅,于是被迫代替她去往敵國和親国夜。 傳聞我的和親對(duì)象是個(gè)殘疾皇子减噪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,167評(píng)論 25 707
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程,因...
    小菜c閱讀 6,424評(píng)論 0 17
  • 首頁 資訊 文章 資源 小組 相親 登錄 注冊(cè) 首頁 最新文章 IT 職場(chǎng) 前端 后端 移動(dòng)端 數(shù)據(jù)庫 運(yùn)維 其他...
    Helen_Cat閱讀 3,878評(píng)論 1 10
  • 其實(shí)车吹,老尚吃苦耐勞的精神我是很佩服的筹裕,原來在隊(duì)里并不起眼的一個(gè)老東西,后來慢慢變成了一個(gè)誰都知道的能掙錢的厲害人窄驹,...
    磨筆團(tuán)廚師長閱讀 245評(píng)論 0 1
  • While these two requirements are met in full by a few cur...
    泰勒不展開閱讀 272評(píng)論 0 0