WeChat 애플릿 개발 제스처 잠금 해제 코드 예

Y2J
풀어 주다: 2017-04-24 14:31:48
원래의
1709명이 탐색했습니다.

제스처 잠금 해제는 앱의 일반적인 잠금 해제 방법으로, 비밀번호를 입력하는 것보다 조작이 훨씬 편리합니다. 다음은 WeChat 애플릿을 기반으로 휴대폰 잠금을 해제하는 방법을 보여줍니다. 최종 효과는 다음과 같습니다.

WeChat 애플릿 개발 제스처 잠금 해제 코드 예

제스처 잠금 해제

전체 기능은 캔버스를 기반으로 합니다. 먼저 캔버스 구성 요소를 추가하고 스타일을 설정하세요.

<!--index.wxml-->
<view class="container">
  <canvas canvas-id="id-gesture-lock" class="gesture-lock" bindtouchstart="onTouchStart"
    bindtouchmove="onTouchMove" bindtouchend="onTouchEnd"></canvas>
</view>

.gesture-lock {
    margin: 100rpx auto;
    width: 300px;
    height: 300px;
    background-color: #ffffff;
}
로그인 후 복사

제스처 잠금 해제 구현 코드는gesture_lock.js에 있습니다(전체 소스 코드 주소는 끝부분을 참조하세요).

초기화

    constructor(canvasid, context, cb, opt){
        this.touchPoints = [];
        this.checkPoints = [];
        this.canvasid = canvasid;
        this.ctx = context;
        this.width = opt && opt.width || 300; //画布长度
        this.height = opt && opt.height || 300; //画布宽度
        this.cycleNum = opt && opt.cycleNum || 3;
        this.radius = 0;  //触摸点半径
        this.isParamOk = false;
        this.marge = this.margeCircle = 25; //触摸点及触摸点和画布边界间隔
        this.initColor = opt && opt.initColor || &#39;#C5C5C3&#39;;   
        this.checkColor = opt && opt.checkColor || &#39;#5AA9EC&#39;;
        this.errorColor = opt && opt.errorColor || &#39;#e19984&#39;;
        this.touchState = "unTouch";
        this.checkParam();
        this.lastCheckPoint = null;
        if (this.isParamOk) {
            // 计算触摸点的半径长度
            this.radius = (this.width - this.marge * 2 - (this.margeCircle * (this.cycleNum - 1))) / (this.cycleNum * 2)
            this.radius = Math.floor(this.radius);
            // 计算每个触摸点的圆心位置
            this.calCircleParams();
        }
        this.onEnd = cb; //滑动手势结束时的回调函数
    }
로그인 후 복사

캔버스의 길이와 너비, 캔버스의 컨텍스트, 제스처 잠금 수(3 x 3)와 같은 일부 매개변수를 주로 설정합니다. , 4번 4), 제스처 잠금 색상, 제스처 슬라이드 종료 시 콜백 기능 등 그리고 제스처 잠금의 반경을 계산합니다.

각 동작 잠금의 중심 위치 계산

    calCircleParams() {
        let n = this.cycleNum;
        let count = 0;
        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++){
                count++;
                let touchPoint = {
                    x: this.marge + i * (this.radius * 2 + this.margeCircle) + this.radius,
                    y: this.marge + j * (this.radius * 2 + this.margeCircle) + this.radius,
                    index: count,
                    check: "uncheck",
                }
                this.touchPoints.push(touchPoint)
            }
        }
    }
로그인 후 복사

동작 잠금 그리기

     for (let i = 0; i < this.touchPoints.length; i++){
            this.drawCircle(this.touchPoints[i].x, this.touchPoints[i].y, this.radius, this.initColor)
     }
     this.ctx.draw(true);
로그인 후 복사

다음 단계는 인식하는 것입니다. 사용자의 스와이프 동작을 통해 사용자가 어느 원을 지나갔는지 확인한 다음 사용자의 제스처를 식별합니다.

touchstarttouchmove 이벤트의 트리거를 감지하고 캔버스를 업데이트합니다.

<p style="margin-bottom: 7px; margin-top: 14px;">   onTouchStart(e) {<br/>        // 不识别多点触控<br/>        if (e.touches.length > 1){<br/>            this.touchState = "unTouch";<br/>            return;<br/>        }<br/>        this.touchState = "startTouch";<br/>        this.checkTouch(e);<br/>        let point = {x:e.touches[0].x, y:e.touches[0].y};<br/>        this.drawCanvas(this.checkColor, point);<br/>    }<br/><br/>    onTouchMove(e) {<br/>        if (e.touchState === "unTouch") {<br/>            return;<br/>        }<br/>        if (e.touches.length > 1){<br/>            this.touchState = "unTouch";<br/>            return;<br/>        }<br/>        this.checkTouch(e);<br/>        let point = {x:e.touches[0].x, y:e.touches[0].y};<br/>        this.drawCanvas(this.checkColor, point);<br/>    }<br/></p>
로그인 후 복사

사용자가 원을 넘었는지 감지

    checkTouch(e) {
        for (let i = 0; i < this.touchPoints.length; i++){
            let point = this.touchPoints[i];
            if (isPointInCycle(e.touches[0].x, e.touches[0].y, point.x, point.y, this.radius)) {
                if (point.check === &#39;uncheck&#39;) {
                    this.checkPoints.push(point);
                    this.lastCheckPoint = point;
                }
                point.check = "check"
                return;
            }
        }
    }
로그인 후 복사

캔버스 업데이트

     drawCanvas(color, point) {
        //每次更新之前先清空画布
        this.ctx.clearRect(0, 0, this.width, this.height);
        //使用不同颜色和形式绘制已触发和未触发的锁
        for (let i = 0; i < this.touchPoints.length; i++){
            let point = this.touchPoints[i];
            if (point.check === "check") {
                this.drawCircle(point.x, point.y, this.radius, color);
                this.drawCircleCentre(point.x, point.y, color);
            }
            else {
                this.drawCircle(this.touchPoints[i].x, this.touchPoints[i].y, this.radius, this.initColor)
            }
        }
        //绘制已识别锁之间的线段
        if (this.checkPoints.length > 1) {
             let lastPoint = this.checkPoints[0];
             for (let i = 1; i < this.checkPoints.length; i++) {
                 this.drawLine(lastPoint, this.checkPoints[i], color);
                 lastPoint = this.checkPoints[i];
             }
        }
        //绘制最后一个识别锁和当前触摸点之间的线段
        if (this.lastCheckPoint && point) {
            this.drawLine(this.lastCheckPoint, point, color);
        }
        this.ctx.draw(true);
    }
로그인 후 복사

사용자의 스와이프가 끝나면 콜백 함수를 호출하고 인식된 제스처를 전달합니다

    onTouchEnd(e) {
        typeof this.onEnd === &#39;function&#39; && this.onEnd(this.checkPoints, false);
    }

    onTouchCancel(e) {
        typeof this.onEnd === &#39;function&#39; && this.onEnd(this.checkPoints, true);
    }
로그인 후 복사

제스처 오류 재설정 및 표시

    gestureError() {
        this.drawCanvas(this.errorColor)
    }

    reset() {
        for (let i = 0; i < this.touchPoints.length; i++) {
            this.touchPoints[i].check = &#39;uncheck&#39;;
        }
        this.checkPoints = [];
        this.lastCheckPoint = null;
        this.drawCanvas(this.initColor);
    }
로그인 후 복사


를 호출하여 onload 메소드에서 잠금 객체를 생성하고 사용자 터치 이벤트에서 해당 메소드를 호출하는 방법

  onLoad: function () {
    var s = this;
    this.lock = new Lock("id-gesture-lock", wx.createCanvasContext("id-gesture-lock"), function(checkPoints, isCancel) {
      console.log(&#39;over&#39;);
      s.lock.gestureError();
      setTimeout(function() {
        s.lock.reset();
      }, 1000);
    }, {width:300, height:300})
    this.lock.drawGestureLock();
    console.log(&#39;onLoad&#39;)
    var that = this
      //调用应用实例的方法获取全局数据
    app.getUserInfo(function(userInfo){
      //更新数据
      that.setData({
        userInfo:userInfo
      })
      that.update()
    })
  },
  onTouchStart: function (e) {
    this.lock.onTouchStart(e);
  },
  onTouchMove: function (e) {
    this.lock.onTouchMove(e);
  },
  onTouchEnd: function (e) {
    this.lock.onTouchEnd(e);
  }
로그인 후 복사

위 내용은 WeChat 애플릿 개발 제스처 잠금 해제 코드 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!