WeChat 애플릿을 통해 제스처 패턴 잠금 화면을 구현하는 방법
이 글은 주로 WeChat 애플릿의 제스처 패턴 잠금 화면 기능을 자세히 소개합니다. 관심 있는 친구가 참고할 수 있습니다.
이 글의 예는 WeChat 애플릿의 제스처 패턴 잠금 화면을 공유합니다. 구체적인 코드는 참고용입니다. 구체적인 내용은 다음과 같습니다
Reference
H5lock
Rendering
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 || 'canvas'; this.cleColor = obj.cleColor || '#CFE6FF'; this.cleCenterColor = obj.cleCenterColor || '#CFE6FF'; var chooseType = obj.chooseType || 3; // 判断是否缓存有chooseType,有就用缓存,没有就用传入的值 this.chooseType = Number(wx.getStorageSync('chooseType')) || chooseType; this.init(); } init(){ this.pswObj = wx.getStorageSync('passwordxx') ? { step: 2, spassword: JSON.parse(wx.getStorageSync('passwordxx')) } : {}; 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:'请解锁'}); } 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 = '', 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; } 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:'密码保存成功'}); this.drawStatusPoint('#2CFF26'); wx.setStorageSync('passwordxx', JSON.stringify(this.pswObj.spassword)); wx.setStorageSync('chooseType', this.chooseType); } else { this.page.setData({ title: '两次不一致,重新输入' }); this.drawStatusPoint('red'); delete this.pswObj.step; } } else if (this.pswObj.step == 2) { if (this.checkPass(this.pswObj.spassword, psw)) { this.page.setData({ title: '解锁成功' }); this.drawStatusPoint('#2CFF26'); } else { this.drawStatusPoint('red'); this.page.setData({ title: '解锁失败' }); } } else { this.pswObj.step = 1; this.pswObj.fpassword = psw; this.page.setData({ title: '再次输入' }); } } 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('passwordxx'); wx.removeStorageSync('chooseType'); this.pswObj = {}; this.page.setData({ title: '绘制解锁图案' }); 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;
위 내용은 제가 정리한 것입니다. 앞으로도 많은 도움이 되었으면 좋겠습니다.
관련 기사:
JS에서 속성 이름에 따옴표를 추가하거나 추가하지 않는 문제
jQuery를 사용하여 마우스 반응 투명도 그라데이션 애니메이션 효과를 얻는 방법
위 내용은 WeChat 애플릿을 통해 제스처 패턴 잠금 화면을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











프론트 엔드 개발시 프론트 엔드 열지대 티켓 인쇄를위한 자주 묻는 질문과 솔루션, 티켓 인쇄는 일반적인 요구 사항입니다. 그러나 많은 개발자들이 구현하고 있습니다 ...

기술 및 산업 요구에 따라 Python 및 JavaScript 개발자에 대한 절대 급여는 없습니다. 1. 파이썬은 데이터 과학 및 기계 학습에서 더 많은 비용을 지불 할 수 있습니다. 2. JavaScript는 프론트 엔드 및 풀 스택 개발에 큰 수요가 있으며 급여도 상당합니다. 3. 영향 요인에는 경험, 지리적 위치, 회사 규모 및 특정 기술이 포함됩니다.

JavaScript는 현대 웹 개발의 초석이며 주요 기능에는 이벤트 중심 프로그래밍, 동적 컨텐츠 생성 및 비동기 프로그래밍이 포함됩니다. 1) 이벤트 중심 프로그래밍을 사용하면 사용자 작업에 따라 웹 페이지가 동적으로 변경 될 수 있습니다. 2) 동적 컨텐츠 생성을 사용하면 조건에 따라 페이지 컨텐츠를 조정할 수 있습니다. 3) 비동기 프로그래밍은 사용자 인터페이스가 차단되지 않도록합니다. JavaScript는 웹 상호 작용, 단일 페이지 응용 프로그램 및 서버 측 개발에 널리 사용되며 사용자 경험 및 크로스 플랫폼 개발의 유연성을 크게 향상시킵니다.

동일한 ID로 배열 요소를 JavaScript의 하나의 객체로 병합하는 방법은 무엇입니까? 데이터를 처리 할 때 종종 동일한 ID를 가질 필요가 있습니다 ...

이 기사에서 시차 스크롤 및 요소 애니메이션 효과 실현에 대한 토론은 Shiseido 공식 웹 사이트 (https://www.shiseido.co.jp/sb/wonderland/)와 유사하게 달성하는 방법을 살펴볼 것입니다.

JavaScript를 배우는 것은 어렵지 않지만 어려운 일입니다. 1) 변수, 데이터 유형, 기능 등과 같은 기본 개념을 이해합니다. 2) 마스터 비동기 프로그래밍 및 이벤트 루프를 통해이를 구현하십시오. 3) DOM 운영을 사용하고 비동기 요청을 처리합니다. 4) 일반적인 실수를 피하고 디버깅 기술을 사용하십시오. 5) 성능을 최적화하고 모범 사례를 따르십시오.

프론트 엔드에서 VSCODE와 같은 패널 드래그 앤 드롭 조정 기능의 구현을 탐색하십시오. 프론트 엔드 개발에서 VSCODE와 같은 구현 방법 ...

Console.log 출력의 차이의 근본 원인에 대한 심층적 인 논의. 이 기사에서는 Console.log 함수의 출력 결과의 차이점을 코드에서 분석하고 그에 따른 이유를 설명합니다. � ...
