Home Web Front-end uni-app How to implement gesture password function in uniapp

How to implement gesture password function in uniapp

Jul 04, 2023 am 10:37 AM
uniapp accomplish Gesture password

How to implement the gesture password function in uniapp

Gesture password is a common way to unlock mobile phones and can also be used in mobile applications developed by uniapp. In uniapp, we can use canvas to draw gesture paths and implement the gesture password function by monitoring the user's gesture operations. This article will introduce how to implement the gesture password function in uniapp and provide relevant code examples.

  1. Create the page structure

First, we need to create a page structure that contains the canvas element. Create a new GestureLock folder in the pages directory and create the GestureLock.vue file in this folder. In the GestureLock.vue file, add the following code:

<template>
  <view class="container">
    <canvas 
      ref="gestureCanvas" 
      canvas-id="gestureCanvas"
      :style="{ width: '100%', height: '100%' }"
    ></canvas>
  </view>
</template>

<script>
export default {
  onLoad() {
    const query = uni.createSelectorQuery().in(this);
    query.select('.container')
      .boundingClientRect((res) => {
        const canvasWidth = res.width;
        const canvasHeight = res.height;
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
        this.ctx = uni.createCanvasContext('gestureCanvas');

        // 绘制初始画面
        this.drawBackground();
      })
      .exec();
  },
  methods: {
    // 绘制背景
    drawBackground() {
      this.ctx.setFillStyle('#F5F5F5');
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.draw();
    },
  },
};
</script>

<style>
.container {
  width: 100vw;
  height: 100vh;
}
</style>
Copy after login

In the above code, we added a canvas element to the page and specified the reference name of the element as gestureCanvas through the ref attribute. And the id of the canvas element is specified as gestureCanvas through the canvas-id attribute. In the component's onLoad method, we use uni.createSelectorQuery().in(this) to obtain the width and height of the canvas element and store it in the component's data. In the component's methods, we define a background drawing method drawBackground(), which is used to draw a gray background on the canvas.

  1. Listen to gesture operations

Next, we need to monitor the user's gesture operations, including finger press, movement and release. We can achieve this function through uniapp's gesture events. In the methods of the GestureLock.vue file, add the following code:

methods: {
  // ...

  // 手指按下事件
  onTouchStart(event) {
    const touch = event.touches[0];
    const startX = touch.clientX;
    const startY = touch.clientY;
    // ...
  },

  // 手指移动事件
  onTouchMove(event) {
    const touch = event.touches[0];
    const moveX = touch.clientX;
    const moveY = touch.clientY;
    // ...
  },

  // 手指松开事件
  onTouchEnd() {
    // ...
  },
},
Copy after login

In the above code, three methods are added to the methods, corresponding to the finger press event, finger move event and finger release event. In the finger press event, we obtain the current finger position through event.touches[0] and store it in the startX and startY variables for subsequent use. In the finger movement event, we obtain the current finger position through event.touches[0] and store it in the moveX and moveY variables for subsequent use. In the finger release event, we can verify the gesture password.

  1. Draw gesture path

Next step, we need to draw the gesture path on the canvas. In the methods of the GestureLock.vue file, add the following code:

methods: {
  // ...

  // 绘制手势路径
  drawGesturePath() {
    this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
    this.drawBackground();
    
    // ...

    this.ctx.setStrokeStyle('#337ab7');
    this.ctx.setLineWidth(3);
    this.ctx.setLineCap('round');
    this.ctx.setLineJoin('round');

    for (let i = 0; i < this.gesturePath.length - 1; i++) {
      const pointA = this.gesturePath[i];
      const pointB = this.gesturePath[i + 1];

      this.ctx.beginPath();
      this.ctx.moveTo(pointA.x, pointA.y);
      this.ctx.lineTo(pointB.x, pointB.y);
      this.ctx.stroke();
    }

    this.ctx.draw(true);
  },
},
Copy after login

In the above code, in the drawGesturePath method, we first use the this.ctx.clearRect() method to clear the content on the canvas, and then call drawBackground method to draw gray background. Next, we use the this.ctx.setStrokeStyle() method to set the color of the line, use the this.ctx.setLineWidth() method to set the width of the line, use the this.ctx.setLineCap() method to set the endpoint style of the line, and use this. The ctx.setLineJoin() method sets the connection style of the line. Then, by traversing the gesturePath array, each line segment of the gesture path is drawn in sequence. Finally, use the this.ctx.draw(true) method to display the drawn content on the canvas in real time.

  1. Complete gesture password function implementation

Finally, we integrate the previous codes to realize the complete gesture password function. In the GestureLock.vue file, add the following code:

<template>
  <view class="container">
    <canvas 
      ref="gestureCanvas" 
      canvas-id="gestureCanvas"
      :style="{ width: '100%', height: '100%' }"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    ></canvas>
  </view>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 0,
      canvasHeight: 0,
      ctx: null,
      startX: 0,
      startY: 0,
      moveX: 0,
      moveY: 0,
      gesturePath: [], // 手势路径的点集合
    };
  },
  onLoad() {
    const query = uni.createSelectorQuery().in(this);
    query.select('.container')
      .boundingClientRect((res) => {
        const canvasWidth = res.width;
        const canvasHeight = res.height;
        this.canvasWidth = canvasWidth;
        this.canvasHeight = canvasHeight;
        this.ctx = uni.createCanvasContext('gestureCanvas');

        // 绘制初始画面
        this.drawBackground();
      })
      .exec();
  },
  methods: {
    // 绘制背景
    drawBackground() {
      this.ctx.setFillStyle('#F5F5F5');
      this.ctx.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.draw();
    },

    // 手指按下事件
    onTouchStart(event) {
      const touch = event.touches[0];
      this.startX = touch.clientX;
      this.startY = touch.clientY;
      this.gesturePath.push({ x: this.startX, y: this.startY });
    },

    // 手指移动事件
    onTouchMove(event) {
      const touch = event.touches[0];
      this.moveX = touch.clientX;
      this.moveY = touch.clientY;
      this.gesturePath.push({ x: this.moveX, y: this.moveY });
      this.drawGesturePath();
    },

    // 手指松开事件
    onTouchEnd() {
      // 进行手势密码的验证
      console.log(this.gesturePath);
    },

    // 绘制手势路径
    drawGesturePath() {
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.drawBackground();

      this.ctx.setStrokeStyle('#337ab7');
      this.ctx.setLineWidth(3);
      this.ctx.setLineCap('round');
      this.ctx.setLineJoin('round');

      for (let i = 0; i < this.gesturePath.length - 1; i++) {
        const pointA = this.gesturePath[i];
        const pointB = this.gesturePath[i + 1];

        this.ctx.beginPath();
        this.ctx.moveTo(pointA.x, pointA.y);
        this.ctx.lineTo(pointB.x, pointB.y);
        this.ctx.stroke();
      }

      this.ctx.draw(true);
    },
  },
};
</script>

<style>
.container {
  width: 100vw;
  height: 100vh;
}
</style>
Copy after login

In the above code, we added three gesture event listeners on the canvas element: @touchstart, @touchmove and @touchend. In the corresponding event processing method, we performed related operations, including obtaining and saving finger positions, drawing and real-time updating of gesture paths, etc. In the finger release event, we can verify the gesture password, such as determining whether the gesture path drawn by the user meets the requirements or is consistent with the preset gesture password.

Through the above steps, we can implement the gesture password function in uniapp. When the user presses his finger and moves it, the gesture path will be displayed on the canvas in real time; when the user releases his finger, we can perform corresponding verification operations based on the gesture path. I hope this article will help you implement the gesture password function in uniapp. If you have any questions, please leave a message for discussion.

The above is the detailed content of How to implement gesture password function in uniapp. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

How to start preview of uniapp project developed by webstorm How to start preview of uniapp project developed by webstorm Apr 08, 2024 pm 06:42 PM

Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Which one is better, uniapp or mui? Which one is better, uniapp or mui? Apr 06, 2024 am 05:18 AM

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

What development tools do uniapp use? What development tools do uniapp use? Apr 06, 2024 am 04:27 AM

UniApp uses HBuilder

What basics are needed to learn uniapp? What basics are needed to learn uniapp? Apr 06, 2024 am 04:45 AM

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

What are the disadvantages of uniapp What are the disadvantages of uniapp Apr 06, 2024 am 04:06 AM

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

See all articles