search
HomeWeb Front-endJS TutorialHow to implement gesture pattern lock screen through WeChat applet

This article mainly introduces the WeChat applet to implement the gesture pattern lock screen function in detail. It has a certain reference value. Interested friends can refer to it.

The example in this article is shared with everyone on WeChat. The specific code of the small program gesture pattern lock screen is for your reference. The specific content is as follows

Reference

H5lock

Rendering

How to implement gesture pattern lock screen through WeChat applet

WXML

<view class="container">
  <view class="reset" bindtap="resetPwd">重置密码</view>
  <view class="title">{{title}}</view>
  <canvas canvas-id="canvas" class="canvas" bindtouchend="onTouchEnd"
   bindtouchstart="onTouchStart" bindtouchmove="onTouchMove"></canvas>
</view>

JS

var Locker = class {
 constructor(page,opt){
  var obj = opt || {};

  this.page = page;
  this.width = obj.width || 300;
  this.height = obj.height || 300;
  this.canvasId = obj.id || &#39;canvas&#39;;
  this.cleColor = obj.cleColor || &#39;#CFE6FF&#39;;
  this.cleCenterColor = obj.cleCenterColor || &#39;#CFE6FF&#39;;

  var chooseType = obj.chooseType || 3;
  // 判断是否缓存有chooseType,有就用缓存,没有就用传入的值
  this.chooseType = Number(wx.getStorageSync(&#39;chooseType&#39;)) || chooseType;

  this.init();
 }
 init(){
  this.pswObj = wx.getStorageSync(&#39;passwordxx&#39;) ? {
   step: 2,
   spassword: JSON.parse(wx.getStorageSync(&#39;passwordxx&#39;))
  } : {};

  this.makeState();
  // 创建 canvas 绘图上下文(指定 canvasId)
  this.ctx = wx.createCanvasContext(this.canvasId,this);
  this.touchFlag = false;
  this.lastPoint = [];

  // 绘制圆
  this.createCircle();
  // canvas绑定事件
  this.bindEvent();
 }
 makeState() {
  if (this.pswObj.step == 2) {
   this.page.setData({ title:&#39;请解锁&#39;});
  } else if (this.pswObj.step == 1) {
   // pass
  } else {
   // pass
  }
 }
 // 画圆方法
 drawCle(x,y){
  // 设置边框颜色。
  this.ctx.setStrokeStyle(this.cleColor); // 注意用set
  // 设置线条的宽度。
  this.ctx.setLineWidth(2); // 注意用set
  // 开始创建一个路径,需要调用fill或者stroke才会使用路径进行填充或描边。
  this.ctx.beginPath();
  // 画一条弧线。
  this.ctx.arc(x, y, this.r, 0, Math.PI * 2, true);
  // 关闭一个路径
  this.ctx.closePath();
  // 画出当前路径的边框。默认颜色色为黑色。
  this.ctx.stroke();
  // 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。
  this.ctx.draw(true);
 }

 // 计算两点之间的距离的方法
 getDis(a, b) {
  return Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
 }

 // 创建解锁点的坐标,根据canvas的大小(默认300px)来平均分配半径
 createCircle() {
  var n = this.chooseType;
  var count = 0;
  // 计算圆半径
  this.r = this.width / (2 + 4 * n);
  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.width, this.height);

  // 绘制所有的圆
  this.arr.forEach(current => {this.drawCle(current.x, current.y);});
 }



 // 设置密码绘制
 getPosition(e) { // 获取touch点相对于canvas的坐标
  var po = {
   x: e.touches[0].x,
   y: e.touches[0].y
  };
  return po;
 }
 precisePosition(po){
  var arr = this.restPoint.filter(current => Math.abs(po.x - current.x) < this.r && Math.abs(po.y - current.y) < this.r);
  return arr[0];
 }
 drawPoint(obj) { // 初始化圆心

  for (var i = 0; i < this.lastPoint.length; i++) {
   this.ctx.setFillStyle(this.cleCenterColor); // 注意用set方法
   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();
   this.ctx.draw(true);
  }
 }
 drawLine(po) {// 解锁轨迹
  this.ctx.beginPath();
  this.ctx.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();
  this.ctx.draw(true);
 }
 pickPoints(fromPt, toPt) {
  var lineLength = this.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 (this.getDis(pt, fromPt) + this.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;
  }
 }
 update(po) {// 核心变换方法在touchmove时候调用
  this.ctx.clearRect(0, 0, this.width, this.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;
   }
  }
 }
 checkPass(psw1, psw2) {// 检测密码
  var p1 = &#39;&#39;,
   p2 = &#39;&#39;;
  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;
 }
 storePass(psw) {// touchend结束之后对密码和状态的处理
  if (this.pswObj.step == 1) {
   if (this.checkPass(this.pswObj.fpassword, psw)) {
    this.pswObj.step = 2;
    this.pswObj.spassword = psw;

    this.page.setData({title:&#39;密码保存成功&#39;});

    this.drawStatusPoint(&#39;#2CFF26&#39;);
    wx.setStorageSync(&#39;passwordxx&#39;, JSON.stringify(this.pswObj.spassword));
    wx.setStorageSync(&#39;chooseType&#39;, this.chooseType);
   } else {
    this.page.setData({ title: &#39;两次不一致,重新输入&#39; });
    this.drawStatusPoint(&#39;red&#39;);
    delete this.pswObj.step;
   }
  } else if (this.pswObj.step == 2) {
   if (this.checkPass(this.pswObj.spassword, psw)) {
    this.page.setData({ title: &#39;解锁成功&#39; });
    this.drawStatusPoint(&#39;#2CFF26&#39;);
   } else {
    this.drawStatusPoint(&#39;red&#39;);
    this.page.setData({ title: &#39;解锁失败&#39; });
   }
  } else {
   this.pswObj.step = 1;
   this.pswObj.fpassword = psw;
   this.page.setData({ title: &#39;再次输入&#39; });
  }
 }
 drawStatusPoint(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();
   this.ctx.draw(true);
  }
 }

 updatePassword() {
  wx.removeStorageSync(&#39;passwordxx&#39;);
  wx.removeStorageSync(&#39;chooseType&#39;);
  this.pswObj = {};
  this.page.setData({ title: &#39;绘制解锁图案&#39; });
  this.reset();
 }
 reset() {
  this.makeState();
  this.createCircle();
 }
 bindEvent(){
  var self = this;
  this.page.onTouchStart = function(e){
   var po = self.getPosition(e);
   self.lastPoint = [];
   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;
    }
   }
  }

  this.page.onTouchMove = function(e){
   if (self.touchFlag) {
    self.update(self.getPosition(e));
   }
  }

  this.page.onTouchEnd = function(e){
   if (self.touchFlag) {
    self.touchFlag = false;
    self.storePass(self.lastPoint);
    setTimeout(function () {
     self.reset();
    }, 300);
   }
  }
 }
}
module.exports = Locker;

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

The problem of adding quotes or not adding quotes to attribute names in JS

How to judge NaN# in JavaScript

##How to use jQuery to implement mouse-responsive transparency gradient animation effect

The above is the detailed content of How to implement gesture pattern lock screen through WeChat applet. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

10 jQuery Syntax Highlighters10 jQuery Syntax HighlightersMar 02, 2025 am 12:32 AM

Enhance Your Code Presentation: 10 Syntax Highlighters for Developers Sharing code snippets on your website or blog is a common practice for developers. Choosing the right syntax highlighter can significantly improve readability and visual appeal. T

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

10  JavaScript & jQuery MVC Tutorials10 JavaScript & jQuery MVC TutorialsMar 02, 2025 am 01:16 AM

This article presents a curated selection of over 10 tutorials on JavaScript and jQuery Model-View-Controller (MVC) frameworks, perfect for boosting your web development skills in the new year. These tutorials cover a range of topics, from foundatio

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools