canvas實現手機的手勢解鎖(步驟詳細)

来源:https://www.cnblogs.com/chenyingying0/archive/2020/03/12/12466325.html
-Advertisement-
Play Games

按照國際慣例,先放效果圖 1、js動態初始化Dom結構 首先在index.html中添加基本樣式 body{background:pink;text-align: center;} 加個移動端meta頭 <meta name="viewport" content="width=device-widt ...


按照國際慣例,先放效果圖

1、js動態初始化Dom結構

首先在index.html中添加基本樣式

body{background:pink;text-align: center;}

加個移動端meta頭

<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">

引入index.js腳本

<script src="index.js"></script>

index.js

// 匿名函數自執行
(function(){
    // canvasLock是全局對象
    window.canvasLock=function(obj){
        this.width=obj.width;
        this.height=obj.height;
    }
    //動態生成DOM
    canvasLock.prototype.initDom=function(){
        //創建一個div
        var div=document.createElement("div");
        var h4="<h4 id='title' class='title'>繪製解鎖圖案</h4>";
        div.innerHTML=h4;
        div.setAttribute("style","position:absolute;top:0;left:0;right:0;bottom:0;");

        //創建canvas
        var canvas=document.createElement("canvas");
        canvas.setAttribute("id","canvas");
        //cssText 的本質就是設置 HTML 元素的 style 屬性值
        canvas.style.cssText="background:pink;display:inine-block;margin-top:15px;";

        div.appendChild(canvas);
        document.body.appendChild(div);

        //設置canvas預設寬高
        var width=this.width||300;
        var height=this.height||300;

        canvas.style.width=width+"px";
        canvas.style.height=height+"px";

        canvas.width=width;
        canvas.height=height;

    }

    
    //init代表初始化,程式的入口
    canvasLock.prototype.init=function(){
        //動態生成DOM
        this.initDom();

        //創建畫布
        this.canvas=document.getElementById("canvas");
        this.ctx=this.canvas.getContext("2d");

    }
})();

在index.html中創建實例並初始化

new canvasLock({}).init();

效果圖

 

 

2、 畫圓函數

需要補充一下畫布寬度與圓的半徑的關係

如果一行3個圓,則有4個間距,間距的寬度與圓的直徑相同,相當於7個直徑,即14個半徑

如果一行4個圓,則有5個間距,間距的寬度與圓的直徑相同,相當於9個直徑,即18個半徑

如果一行n個圓,則有n+1個間距,間距的寬度與圓的直徑相同,相當於2n+1個直徑,即4n+2個半徑

 

 

補充兩個方法:

//以給定坐標點為圓心畫出單個圓
    canvasLock.prototype.drawCircle=function(x,y){
        this.ctx.strokeStyle="#abcdef";
        this.ctx.lineWidth=2;
        this.ctx.beginPath();
        this.ctx.arc(x,y,this.r,0,2*Math.PI,true);
        this.ctx.closePath();
        this.ctx.stroke();
    }
    
    //繪製出所有的圓
    canvasLock.prototype.createCircle=function(){
        var n=this.circleNum;//一行幾個圓
        var count=0;
        this.r=this.canvas.width/(4*n+2);//公式計算出每個圓的半徑
        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:(4*j+3)*r,
                    y:(4*i+3)*r,
                    index:count//給每個圓標記索引
                };
                this.arr.push(obj);
                this.restPoint.push(obj);//初始化時為所有點
            }
        }

        //清屏
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);

        //以給定坐標點為圓心畫出所有圓
        for(var i=0;i<this.arr.length;i++){
            //迴圈調用畫單個圓的方法
            this.drawCircle(this.arr[i].x,this.arr[i].y);
        }

    }

初始化的時候記得調用

canvasLock.prototype.init=function(){
        //動態生成DOM
        this.initDom();

        //創建畫布
        this.canvas=document.getElementById("canvas");
        this.ctx=this.canvas.getContext("2d");

        //繪製出所有的圓
        this.createCircle();
    }

別忘了在index.html中實例化時傳入參數(一行定義幾個圓)

new canvasLock({circleNum:3}).init();

效果圖

 

 

3、canvas事件操作——實現畫圓和畫線

getPosition方法用來得到滑鼠觸摸點離canvas的距離(左邊和上邊)

canvasLock.prototype.getPosition=function(e){
        var rect=e.currentTarget.getBoundingClientRect();//獲得canvas距離屏幕的上下左右距離
        var po={
            //滑鼠與視口的左距離 - canvas距離視口的左距離 = 滑鼠與canvas的左距離
            x:(e.touches[0].clientX-rect.left),
            //滑鼠與視口的上距離 - canvas距離視口的上距離 = 滑鼠距離canvas的上距離
            y:(e.touches[0].clientY-rect.top)
        };
        return po;
    }

給canvas添加 touchstart 事件,判斷觸摸點是否在圓內

觸摸點在圓內則允許拖拽,並將該圓添加到 lastPoint 中,從 restPoint 中剔除

this.canvas.addEventListener("touchstart",function(e){
            var po=self.getPosition(e);//滑鼠距離canvas的距離

            //判斷是否在圓內
            for(var i=0;i<self.arr.lenth;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.lastPoint.push(self.arr[i]);//點擊過的點
                    self.restPoint.splice(i,1);//剩下的點剔除這個被點擊的點
                    break;
                }
            }
        },false);

 

判斷是否在圓內的原理:

 

 圓心的x軸偏移和滑鼠點的x軸偏移的距離的絕對值小於半徑

並且

 圓心的y軸偏移和滑鼠點的y軸偏移的距離的絕對值小於半徑

則可以判斷滑鼠位於圓內

 

給touchmove綁定事件,在觸摸點移動時給點擊過的圓畫上實心圓,並畫線

//觸摸點移動時的動畫
    canvasLock.prototype.update=function(po){
        //清屏,canvas動畫前必須清空原來的內容
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);

        //以給定坐標點為圓心畫出所有圓
        for(var i=0;i<this.arr.length;i++){
            this.drawCircle(this.arr[i].x,this.arr[i].y);
        }

        this.drawPoint();//點擊過的圓畫實心圓
        this.drawLine(po);//畫線

    }

    //畫實心圓
    canvasLock.prototype.drawPoint=function(){
        for(var i=0;i<this.lastPoint.length;i++){
            this.ctx.fillStyle="#abcdef";
            this.ctx.beginPath();
            this.ctx.arc(this.lastPoint[i].x,this.lastPoint[i].y,this.r/2,0,2*Math.PI,true);
            this.ctx.closePath();
            this.ctx.fill();
        }
    }

    //畫線
    canvasLock.prototype.drawLine=function(po){
        this.ctx.beginPath();
        this.lineWidth=3;
        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();
    }

效果圖

 

 

4、canvas手勢鏈接操作實現

在touchmove中補充當碰到下一個目標圓時的操作

//碰到下一個圓時只需要push到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.lastPoint.push(this.restPoint[i]);//將這個新點擊到的點存入lastPoint
                this.restPoint.splice(i,1);//從restPoint中剔除這個新點擊到的點
                break;
            }
        }

效果圖

 

 

5、解鎖成功與否的判斷

 

//設置密碼
    canvasLock.prototype.storePass=function(){
        if(this.checkPass()){
            document.getElementById("title").innerHTML="解鎖成功";
            this.drawStatusPoint("lightgreen");
        }else{
            document.getElementById("title").innerHTML="解鎖失敗";
            this.drawStatusPoint("orange");
        }
    }

    //判斷輸入的密碼
    canvasLock.prototype.checkPass=function(){
        var p1="123",//成功的密碼
            p2="";
        for(var i=0;i<this.lastPoint.length;i++){
            p2+=this.lastPoint[i].index;
        }
        return p1===p2;
    }

    //繪製判斷結束後的狀態
    canvasLock.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,2*Math.PI,true);
            this.ctx.closePath();
            this.ctx.stroke();
        }
    }

    //程式全部結束後重置
    canvasLock.prototype.reset=function(){
        this.createCircle();
    }

 

大功告成!!下麵曬出所有代碼

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>手勢解鎖</title>
    <!-- 移動端meta頭 -->
    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">
    <style>
           body{background:pink;text-align: center;}
    </style>
</head>
<body>

    <script src="index.js"></script>
    <script>
        // circleNum:3 表示一行3個圓
        new canvasLock({circleNum:3}).init();
    </script>
  
</body>
</html>

index.js

// 匿名函數自執行
(function(){
    // canvasLock是全局對象
    window.canvasLock=function(obj){
        this.width=obj.width;
        this.height=obj.height;
        this.circleNum=obj.circleNum;
    }
    //動態生成DOM
    canvasLock.prototype.initDom=function(){
        //創建一個div
        var div=document.createElement("div");
        var h4="<h4 id='title' class='title'>繪製解鎖圖案</h4>";
        div.innerHTML=h4;
        div.setAttribute("style","position:absolute;top:0;left:0;right:0;bottom:0;");

        //創建canvas
        var canvas=document.createElement("canvas");
        canvas.setAttribute("id","canvas");
        //cssText 的本質就是設置 HTML 元素的 style 屬性值
        canvas.style.cssText="background:pink;display:inine-block;margin-top:15px;";

        div.appendChild(canvas);
        document.body.appendChild(div);

        //設置canvas預設寬高
        var width=this.width||300;
        var height=this.height||300;

        canvas.style.width=width+"px";
        canvas.style.height=height+"px";

        canvas.width=width;
        canvas.height=height;

    }

    //以給定坐標點為圓心畫出單個圓
    canvasLock.prototype.drawCircle=function(x,y){
        this.ctx.strokeStyle="#abcdef";
        this.ctx.lineWidth=2;
        this.ctx.beginPath();
        this.ctx.arc(x,y,this.r,0,2*Math.PI,true);
        this.ctx.closePath();
        this.ctx.stroke();
    }
    
    //繪製出所有的圓
    canvasLock.prototype.createCircle=function(){
        var n=this.circleNum;//一行幾個圓
        var count=0;
        this.r=this.canvas.width/(4*n+2);//公式計算出每個圓的半徑
        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:(4*j+3)*r,
                    y:(4*i+3)*r,
                    index:count//給每個圓標記索引
                };
                this.arr.push(obj);
                this.restPoint.push(obj);//初始化時為所有點
            }
        }

        //清屏
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);

        //以給定坐標點為圓心畫出所有圓
        for(var i=0;i<this.arr.length;i++){
            //迴圈調用畫單個圓的方法
            this.drawCircle(this.arr[i].x,this.arr[i].y);
        }

    }

    //添加事件
    canvasLock.prototype.bindEvent=function(){
        var self=this;

        this.canvas.addEventListener("touchstart",function(e){
            var po=self.getPosition(e);//滑鼠距離canvas的距離

            //判斷是否在圓內
            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.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.storePass(self.lastPoint);
                setTimeout(function(){
                    self.reset();
                },300);
            }
        },false);

    }

    //設置密碼
    canvasLock.prototype.storePass=function(){
        if(this.checkPass()){
            document.getElementById("title").innerHTML="解鎖成功";
            this.drawStatusPoint("lightgreen");
        }else{
            document.getElementById("title").innerHTML="解鎖失敗";
            this.drawStatusPoint("orange");
        }
    }

    //判斷輸入的密碼
    canvasLock.prototype.checkPass=function(){
        var p1="123",//成功的密碼
            p2="";
        for(var i=0;i<this.lastPoint.length;i++){
            p2+=this.lastPoint[i].index;
        }
        return p1===p2;
    }

    //繪製判斷結束後的狀態
    canvasLock.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,2*Math.PI,true);
            this.ctx.closePath();
            this.ctx.stroke();
        }
    }

    //程式全部結束後重置
    canvasLock.prototype.reset=function(){
        this.createCircle();
    }
    
    //獲取滑鼠點擊處離canvas的距離
    canvasLock.prototype.getPosition=function(e){
        var rect=e.currentTarget.getBoundingClientRect();//獲得canvas距離屏幕的上下左右距離
        var po={
            //滑鼠與視口的左距離 - canvas距離視口的左距離 = 滑鼠與canvas的左距離
            x:(e.touches[0].clientX-rect.left),
            //滑鼠與視口的上距離 - canvas距離視口的上距離 = 滑鼠距離canvas的上距離
            y:(e.touches[0].clientY-rect.top)
        };
        return po;
    }

    //觸摸點移動時的動畫
    canvasLock.prototype.update=function(po){
        //清屏,canvas動畫前必須清空原來的內容
        this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height);

        //以給定坐標點為圓心畫出所有圓
        for(var i=0;i<this.arr.length;i++){
            this.drawCircle(this.arr[i].x,this.arr[i].y);
        }

        // 滑鼠每移動一下都會重繪canvas,update操作相當於每一個move事件都會觸發
        this.drawPoint();//點擊過的圓畫實心圓
        this.drawLine(po);//畫線

        //碰到下一個圓時只需要push到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.lastPoint.push(this.restPoint[i]);//將這個新點擊到的點存入lastPoint
                this.restPoint.splice(i,1);//從restPoint中剔除這個新點擊到的點
                break;
            }
        }
    }

    //畫實心圓
    canvasLock.prototype.drawPoint=function(){
        for(var i=0;i<this.lastPoint.length;i++){
            this.ctx.fillStyle="#abcdef";
            this.ctx.beginPath();
            this.ctx.arc(this.lastPoint[i].x,this.lastPoint[i].y,this.r/2,0,2*Math.PI,true);
            this.ctx.closePath();
            this.ctx.fill();
        }
    }

    //畫線
    canvasLock.prototype.drawLine=function(po){
        this.ctx.beginPath();
        this.lineWidth=3;
        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();
    }

    //init代表初始化,程式的入口
    canvasLock.prototype.init=function(){
        //動態生成DOM
        this.initDom();

        //創建畫布
        this.canvas=document.getElementById("canvas");
        this.ctx=this.canvas.getContext("2d");

        //預設不允許拖拽
        this.touchFlag=false;

        //繪製出所有的圓
        this.createCircle();

        //添加事件
        this.bindEvent();
    }
})();

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 我之前用sqlserver連過很多人的資料庫,後來我怕登陸的時候登陸錯了,想清楚一下連接那裡的預設記錄,後來在網上找過許多方法都不行,後來誤打誤撞找到了方法,大家可以試一下下邊的方法: 有的直接放在User/AppData文件夾下邊,總之就是找到Shell文件,然後刪掉就可以了,這個辦法我試過是可以 ...
  • 更新索引至最大值:select setval('"demo".test_id_seq', (SELECT MAX("id") FROM demo.test)); 查詢下一個序列值:select nextval('"demo".test_id_seq'); ...
  • shell 腳本操作informix資料庫的簡單模板: functionName(){ dbaccess << ! database 庫名; sql語句; ! } 慄子1:更新數據 functionName(){ nameStr=$1 idStr=$2 dbaccess << ! database ...
  • 這樣如果備份的時候如果出現錯誤,那就看不出是哪裡出的問題,所以需要解決。 經過在網上查詢相關資料發現是客戶端字元集設置的和資料庫的字元集設置的不一致 資料庫的字元集查看語句為 select * from nls_database_parameters; 結果為utf-8字元集 那麼就需要將客戶端的字 ...
  • 開心一刻 樓主:心都讓你嚇出來了! 獅王:淡定,打個小噴嚏而已 前情回顧 神奇的 SQL 之 聯表細節 → MySQL JOIN 的執行過程(一)中,我們講到了 3 種聯表演算法:SNL、BNL 和 INL,瞭解了數據的查詢方式是 one by one,聯表方式也是 one by one ;並談到了 ...
  • MySql 是一種免費的關係型資料庫,相較於 MsSqlServer 和 Oracle 比較輕量化,安裝也很簡單,而且免費不需要的版權費用,個人認為一般的小項目採用還是比較合適的,當然也有部分數據量很大的項目會採用 MySql,不過個人認為 MySql 的多錶鏈接查詢能力不行,一但去組成 3個表以上 ...
  • 註意:無特殊說明,Flutter版本及Dart版本如下: Flutter版本: 1.12.13+hotfix.5 Dart版本: 2.7.0 ClipRect ClipRect組件使用矩形裁剪子組件,通常情況下,ClipRect作用於 、 、 、 、 、 、 組件,例如ClipRect作用於Alig ...
  • 教程/Articles 1. "說說 Flutter 中最熟悉的陌生人 —— Key" 插件/Librarys 1. "dna" 一個 flutter plugin. 輕量級的Dart到Native的超級通道,可直接在dart代碼中調用原生代碼,目前支持安卓 JAVA 和 iOS ObjC. 1. ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...