h5手勢解鎖

h5基於canvas手勢解鎖

效果圖javascript

源碼

(function(){
        window.H5lock = function(obj){
            this.version=function(){console.log('1.0.0')};
            this.author='chason';
            var w = document.documentElement.clientWidth || document.body.clientWidth;
            var h = document.documentElement.clientHeight || document.body.clientHeight;
            this.height = obj.height?obj.height:h;
            this.width = obj.width?obj.width:w;
            this.bg=obj.bg?obj.bg:"#000";
            this.notice=obj.noticeEl;
            this.pswEl=obj.pswEl;
            this.type=obj.type;
            this.position=obj.position?obj.position:{left:0,top:0};
            this.savePws=obj.savePws?obj.savePws:function(psw){};
            this.lockSuccess=obj.lockSuccess?obj.lockSuccess:function(){};
            this.resetPswText=obj.resetPswText?obj.resetPswText:'重置密碼';
            this.initialNoticel=obj.initialNoticel?obj.initialNoticel:'請繪製解鎖圖案';
            this.chooseType = Number(window.localStorage.getItem('chooseType')) || obj.chooseType;
            this.devicePixelRatio = window.devicePixelRatio || 1;

            document.querySelector(this.notice).innerHTML=this.initialNoticel;
            document.querySelector(this.pswEl).innerHTML=this.resetPswText;
            (this.type=='unlock') && (document.querySelector(this.pswEl).style.display='none');
        };


        H5lock.prototype.drawCle = function(x, y) { // 初始化解鎖密碼面板 小圓圈
            this.ctx.strokeStyle = '#87888a';//密碼的點點默認的顏色
            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(style) { // 初始化圓心
            for (var i = 0 ; i < this.lastPoint.length ; i++) {
                this.ctx.fillStyle = style;
                this.ctx.beginPath();
                this.ctx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2.5, 0, Math.PI * 2, true);
                this.ctx.closePath();
                this.ctx.fill();
            }
        }
        H5lock.prototype.drawStatusPoint = function(type) { // 初始化狀態線條
            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(style, po, lastPoint) {//style:顏色 解鎖軌跡
            this.ctx.beginPath();
            this.ctx.strokeStyle = style;
            this.ctx.lineWidth = 3;
            (this.lastPoint[0]) && (this.ctx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y));

            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() {// 建立解鎖點的座標,根據canvas的大小來平均分配半徑

            var n = this.chooseType;
            var count = 0;
            this.r = this.ctx.canvas.width / (1 + 4 * n);// 公式計算
            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 + 2.5 * r,
                        y: i * 4 * r + 3 * r+5*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點相對於canvas的座標
            var rect = e.currentTarget.getBoundingClientRect();
            var po = {
                x: (e.touches[0].clientX - rect.left)*this.devicePixelRatio,
                y: (e.touches[0].clientY - rect.top)*this.devicePixelRatio
              };
            return po;
        }
        H5lock.prototype.update = function(po) {// 核心變換方法在touchmove時候調用
            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('#27AED5');// 每幀花軌跡
            this.drawStatusPoint('#27AED5');// 每幀花軌跡

            this.drawLine('#27AED5',po , this.lastPoint);// 每幀畫圓心


            for (var i = 0 ; i < this.restPoint.length ; i++) {
                if (Math.abs(po.x - this.restPoint[i].x) < this.r && Math.abs(po.y - this.restPoint[i].y) < this.r) {
                    this.drawPoint(this.restPoint[i].x, this.restPoint[i].y);
                    this.lastPoint.push(this.restPoint[i]);
                    this.restPoint.splice(i, 1);
                    break;
                }
            }

        }
        H5lock.prototype.checkPass = function(psw1, psw2) {// 檢測密碼
            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結束以後對密碼和狀態的處理

            if (this.pswObj.step == 1) {
                if (this.checkPass(this.pswObj.fpassword, psw)) {
                    this.pswObj.step = 2;
                    this.pswObj.spassword = psw;
                    document.querySelector(this.notice).innerHTML = '密碼保存成功';
                    this.drawStatusPoint('#2CFF26');
                    this.drawPoint('#2CFF26');
                    window.localStorage.setItem('passwordxx', JSON.stringify(this.pswObj.spassword));
                    window.localStorage.setItem('chooseType', this.chooseType);
                    this.savePws(this.pswObj.spassword)
                } else {
                    document.querySelector(this.notice).innerHTML='兩次不一致,從新輸入';
                    this.drawStatusPoint('red');
                    this.drawPoint('red');
                    delete this.pswObj.step;
                }
            } else if (this.pswObj.step == 2) {
                if (this.checkPass(this.pswObj.spassword, psw)) {
                    var title = document.querySelector(this.notice);
                    title.style.color = "#2CFF26";
                    title.innerHTML = '解鎖成功';

                    this.drawStatusPoint('#2CFF26');//小點點外圈高亮
                    this.drawPoint('#2CFF26');
                    this.drawLine('#2CFF26',this.lastPoint[this.lastPoint.length-1] , this.lastPoint);// 每幀畫圓心
                    this.lockSuccess();

                } else if (psw.length < 4) {

                    this.drawStatusPoint('red');
                    this.drawPoint('red');
                    this.drawLine('red',this.lastPoint[this.lastPoint.length-1] , this.lastPoint);// 每幀畫圓心

                    var title = document.querySelector(this.notice);
                    title.style.color = "red";
                    title.innerHTML = '請至少鏈接4個點';

                } else {
                    this.drawStatusPoint('red');
                    this.drawPoint('red');
                    this.drawLine('red',this.lastPoint[this.lastPoint.length-1] , this.lastPoint);// 每幀畫圓心


                    var title = document.querySelector(this.notice);
                    title.style.color = "red";
                    title.innerHTML = '密碼錯誤,您還能夠輸入N次';
                }
            } else {
                if(psw.length<4){
                  document.querySelector(this.notice).innerHTML = '請至少鏈接4個點';
                  return;
                }
                this.pswObj.step = 1;
                this.pswObj.fpassword = psw;
                document.querySelector(this.notice).innerHTML = '再次輸入';
            }

        }
        H5lock.prototype.makeState = function() {
            if (this.pswObj.step == 2) {
                (this.type=='reset') && (document.querySelector(this.pswEl).style.display = 'block');

                var title = document.querySelector(this.notice);
                title.style.color = "#87888a";
                title.innerHTML = '請解鎖';

            } else if (this.pswObj.step == 1) {
                (this.type=='reset') && (document.querySelector(this.pswEl).style.display = 'none');
            } else {
                (this.type=='reset') && (document.querySelector(this.pswEl).style.display = 'none');
            }
        }
        H5lock.prototype.setChooseType = function(type){
            chooseType = type;
            init();
        }
        H5lock.prototype.updatePassword = function(){
            window.localStorage.removeItem('passwordxx');
            window.localStorage.removeItem('chooseType');
            this.pswObj = {};
            document.querySelector(this.notice).innerHTML =this.initialNoticel;
            this.reset();
        }
        H5lock.prototype.initDom = function(){
            var wrap = document.createElement('div');
            wrap.setAttribute('style','position: absolute;top:0;left:0;right:0;bottom:0;');
            var canvas = document.createElement('canvas');
            canvas.setAttribute('id','canvas');
            canvas.style.cssText = 'background-color:'+this.bg+';position:absolute;top:'+this.position.top+'px;left:'+this.position.left+'px;z-index:1;';
            wrap.appendChild(canvas);

            var width = this.width;
            var height = this.height;

            document.body.appendChild(wrap);

            // 高清屏鎖放
            canvas.style.width = width + "px";
            canvas.style.height = height + "px";
            canvas.height = height * this.devicePixelRatio;
            canvas.width = width * this.devicePixelRatio;


        }
        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();
            //判斷是type是reset仍是unlock
            if(this.type=='reset'){
               this.updatePassword();
            }
        }
        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不宜觸發 因此增長此行代碼
                 var po = self.getPosition(e);

                 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();
                    }, 1000);
                 }


             }, false);

             document.querySelector(this.pswEl).addEventListener('click', function(){
                 self.updatePassword();
              });
        }
})();

使用方法

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <title>title</title>
    <!--  -->
    <style>
        #notice{
          position: absolute;
          top:20vh;
          left:0;
          width:100%;
          z-index: 5;
          text-align: center;
          color: rgb(135, 136, 138);
        }
        #reset{
          position: absolute;
          bottom:15vh;
          right:0;
          width:100%;
          z-index: 5;
          text-align: center;
          color: rgb(135, 136, 138);
        }
    </style>
    <div id="gesture">
        <p id="notice"></p>
        <p id="reset"></p>
    </div>
</head>

<body>

</body>

<script src="../../../plugin/h5lock/H5lock.js"></script>
<script type="text/javascript">
      var opt={
          chooseType:3,//必須字段,幾排幾列
          width:414,//canvas寬度,默認100%
          height:736,//canvaas高度,默認100%
          //canvas位置,默認left:0,top:0,若是你的canvas寬高默認100%,此值可不填
          position:{
            left:0,
            top:0
          },
          bg:"#000",//canvas背景,默認#000
          noticeEl:"#notice",//必須字段:提示的容器,因canvas absolute定位,因此注意層疊關係
          pswEl:"#reset",//必須字段:重置密碼的容器,因canvas absolute定位,因此注意層疊關係
          initialNoticel:"請繪製解鎖圖案",//提示解鎖的文本,默認"請繪製解鎖圖案"
          resetPswText:"重置密碼",//重置密碼的文本,默認'重置密碼',
          type:"reset",//必須字段,當前是設置手勢仍是解鎖,reset和unlock
          //type='reset'的保存密碼後執行,返回密碼obj
          savePws:function(psw){
            alert(JSON.stringify(psw));
          },
          //解鎖成功
          lockSuccess:function(){
            alert('解鎖成功');
          }

      }
      var lock=new H5lock(opt);
      lock.init();
</script>

</html>
相關文章
相關標籤/搜索