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

Vue.js implements tab switching and color change operation explanation

When implementing this function, the method I bor...

Tutorial on installing mongodb under linux

MongoDB is cross-platform and can be installed on...

How to Develop a Progressive Web App (PWA)

Table of contents Overview Require URL of the app...

MySQL 5.7 generated column usage example analysis

This article uses examples to illustrate the usag...

Use of MySQL triggers

Triggers can cause other SQL code to run before o...

CUDA8.0 and CUDA9.0 coexist under Ubuntu16.04

Preface Some of the earlier codes on Github may r...

The combination and difference between ENTRYPOINT and CMD in dockerfile

In the previous article [Detailed explanation of ...

How MySQL handles implicit default values

Some students said that they encountered the prob...

Screen command and usage in Linux

Screen Introduction Screen is a free software dev...

Install docker offline by downloading rpm and related dependencies using yum

You can use yum to install all dependencies toget...

Detailed explanation of the flexible use of CSS grid system in projects

Preface CSS grids are usually bundled in various ...

Specific use of MySQL internal temporary tables

Table of contents UNION Table initialization Exec...