WeChat applet implements a simple handwritten signature component

WeChat applet implements a simple handwritten signature component

background:

During the project, it is necessary to implement a handwritten signature component in the WeChat applet. I searched the Internet for WeChat mini-programs to implement handwritten signatures, but the results were not ideal. In actual application, lag may occur due to the real-time calculation of a large number of Bezier curves. The effect is not ideal. So taking a step back, there is no need for pen tip and handwriting simulation effects. All it requires is a simple handwritten signature.

need:

It allows users to handwrite signatures on WeChat mini programs.

Need to be componentized.

Effect

1. Idea

In the WeChat applet, we use the canvas component to implement it. Think of the user input as a pen. The signature we are going to draw is made up of many points. But simple points cannot form a line very well. The points must also be connected by lines. The following is the implementation code.

2. Implementation

1. Pages and styles

wxml

The canvas component here is the latest usage.

<view class="dashbox">
  <view class="btnList">
    <van-button size="small" bind:click="clearCanvas">Clear</van-button>
  </view>
  <view class="handCenter">
    <canvas 
      class="handWriting" 
      disable-scroll="{{true}}" 
      id="handWriting"
      bindtouchstart="scaleStart"
      bindtouchmove="scaleMove" 
      bindtouchend="scaleEnd"
      bindtap="mouseDown"
      type="2d"
    >
    </canvas>
  </view>
</view>

wxss

.btnList{
    width: 95%;
    margin:0 auto;
}
.handWriting{
    background: #fff;
    width: 95%;
    height: 80vh;
    margin:0 auto
}

2. Initialization

Since it is used in a custom component, pay attention to the this pointing problem when getting the canvas. If you do not call the In method of SelectorQuery, you will not be able to get the canvas in the custom component because it points to the parent component at this time.

Component({
 /**
 * Initial data of the component */
    data: {
        canvasName:'#handWriting',
        ctx:'',
        canvasWidth:0,
        canvasHeight:0,
        startPoint:{
            x:0,
            y:0,
        },
        selectColor: 'black',
        lineColor: '#1A1A1A', // color lineSize: 1.5, // note multiple radius: 5, // radius of the circle}, 
    ready(){
        let canvasName = this.data.canvasName;
        let query = wx.createSelectorQuery().in(this); //Get the SelectQuery object of the custom component query.select(canvasName)
        .fields({ node: true, size: true })
        .exec((res) => {
          const canvas = res[0].node;
          const ctx = canvas.getContext('2d');
          //Get device pixel ratio const dpr = wx.getSystemInfoSync().pixelRatio;
          //Scale and set the canvas size to prevent handwriting dislocation canvas.width = res[0].width * dpr;
          canvas.height = res[0].height * dpr;
          ctx.scale(dpr, dpr);
          ctx.lineJoin="round";
          this.setData({ctx});
        });
  
        query.select('.handCenter').boundingClientRect(rect => {
            console.log('rect', rect);
            this.setData({
                canvasWidth:rect.width,
                canvasHeight:rect.height
            });
        }).exec();
    },
   //Omit the following code...
});

3. When clicking

Component({
 //Omit the above code...
 methods: {
            scaleStart(event){
                if (event.type != 'touchstart') return false;
                let currentPoint = {
                    x: event.touches[0].x,
                    y: event.touches[0].y
                }
                this.drawCircle(currentPoint);
                this.setData({startPoint:currentPoint});
          },
            drawCircle(point){//Here is responsible for the point let ctx = this.data.ctx;
                ctx.beginPath();
                ctx.fillStyle = this.data.lineColor;
            //The thickness of the handwriting is determined by the size of the circle ctx.arc(point.x, point.y, this.data.radius, 0 , 2 * Math.PI);
                ctx.fill();
                ctx.closePath();
          },
          //Omit the following code...
 }
})

4. Signature

Component({
  //Omit the above code methods:{
 drawLine(sourcePoint, targetPoint){
            let ctx = this.data.ctx;
            this.drawCircle(targetPoint);
            ctx.beginPath();
            ctx.strokeStyle = this.data.lineColor;
            ctx.lineWidth = this.data.radius * 2; //The reason for multiplying by 2 here is that the thickness of the line should be equal to the diameter of the circle ctx.moveTo(sourcePoint.x, sourcePoint.y);
            ctx.lineTo(targetPoint.x, targetPoint.y);
            ctx.stroke();
            ctx.closePath();
          },
          clearCanvas(){//Clear the canvas let ctx = this.data.ctx;
            ctx.rect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
            ctx.fillStyle = '#FFFFFF';
            ctx.fill();
          }
  }
})

Conclusion

This handwritten signature is for business emergency use only. If you want to optimize, you can start with pen stroke simulation and handwriting simulation. The only problem that needs to be solved is the lag during real-time simulation.

This is the end of this article about how to implement a simple handwritten signature component in WeChat Mini Program. For more relevant content about the handwritten signature component of WeChat Mini Program, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Uniapp implements electronic signature effect of WeChat applet (with demo)
  • Sample code for implementing handwritten signature in WeChat applet
  • WeChat Mini Program to Implement Electronic Signature
  • WeChat applet canvas implements signature function
  • WeChat Mini Program implements electronic signature function
  • WeChat applet implements electronic signature and exports images
  • Java encountered WeChat applet "payment verification signature failed" problem solution
  • .NET WeChat applet user data signature verification and decryption code
  • WeChat applet implements horizontal and vertical screen signature function

<<:  Awk command line or script that helps you sort text files (recommended)

>>:  Solve the problem that the Node.js mysql client does not support the authentication protocol

Recommend

Detailed explanation of the basic usage of SSH's ssh-keygen command

SSH public key authentication is one of the SSH a...

A few things you need to know about responsive layout

1. Introduction Responsive Web design allows a we...

Web page experience: planning and design

1. Clarify the design direction <br />First,...

Detailed steps for manually configuring the IP address in Linux

Table of contents 1. Enter the network card confi...

How to use explain to query SQL execution plan in MySql

The explain command is the primary way to see how...

Detailed process of configuring NIS in Centos7

Table of contents principle Network environment p...

Analysis of HTTP interface testing process based on postman

I accidentally discovered a great artificial inte...

Analysis and treatment of scroll bars in both HTML and embedded Flash

We often encounter this situation when doing devel...

How to use Docker to build a pypi private repository

1. Construction 1. Prepare htpasswd.txt file The ...

How to use vue filter

Table of contents Overview Defining filters Use o...

Vue template compilation details

Table of contents 1. parse 1.1 Rules for intercep...

Mycli is a must-have tool for MySQL command line enthusiasts

mycli MyCLI is a command line interface for MySQL...

Docker data volume container creation and usage analysis

A data volume container is a container specifical...

How to simply configure multiple servers in nginx

1: I won’t go into the details of how to install ...

Use Docker to build a Redis master-slave replication cluster

In a cluster with master-slave replication mode, ...