WeChat Mini Program to Implement Electronic Signature

WeChat Mini Program to Implement Electronic Signature

This article shares the specific code for implementing electronic signatures in WeChat Mini Programs for your reference. The specific content is as follows

<view class="sign-contain">
 <view class="signName">
  <canvas id="canvas" canvas-id="canvas" class="{{ sysType === 'iOS' ? 'canvas' : 'canvas bg000'}}" disable-scroll="true" bindtouchstart="canvasStart" bindtouchmove="canvasMove" bindtouchend="canvasEnd" touchcancel="canvasEnd" binderror="canvasIdErrorCallback"></canvas>
 </view>

 <view class="btn-wrap">
  <button catchtap="cleardraw">Clear signature</button>
  <button catchtap="uploadImg">Upload signature</button>
 </view>
</view>

js:

var context = null; // Use wx.createContext to get the drawing context context
var isButtonDown = false; //Whether drawing is in progress var arrx = []; //Action horizontal coordinate var arry = []; //Action vertical coordinate var arrz = []; //Total state, marking a combination of pressing and lifting var canvasw = 0; //Canvas width var canvash = 0; //Canvas height Page({
  data: {
    canvasw: '',
    canvash: '',
    imgUrl: '',
    info: {},
    signBase64: '',
    sysType: '' // Determine the model},

  onLoad: function (options) {
    let that = this
    let res = wx.getSystemInfoSync()
    const system = res.system.split(' ')
    that.setData({
      sysType: system[0],
    })
    let params = JSON.parse(options.params)
    that.setData({
      info: params,
    })
    that.startCanvas();
    that.initCanvas()
  },
  /**
  * Below - Handwritten Signature/ Upload Signature*/
  startCanvas() {//Canvas initialization execution var that = this;
    //Get system information wx.getSystemInfo({
      success: function (res) {
        canvasw = res.windowWidth;
        canvash = res.windowHeight;
        that.setData({ canvasw: canvasw });
        that.setData({ canvash: canvash });
      }
    });
    this.initCanvas();
    this.cleardraw();
  },

  // Initialization function initCanvas() {
    context = wx.createCanvasContext('canvas');
    context.beginPath()
    if(this.data.sysType === 'iOS') {
      context.fillStyle = 'rgba(255, 255, 255, 1)';
      context.setStrokeStyle('#444');
    } else {
      context.fillStyle = 'rgba(0, 0, 0, 1)';
      context.setStrokeStyle('#aaa');
    }
    context.setLineWidth(4);
    context.setLineCap('round');
    context.setLineJoin('round');
  },
  canvasStart(event) {
    isButtonDown = true;
    arrz.push(0);
    arrx.push(event.changedTouches[0].x);
    arry.push(event.changedTouches[0].y);
  },
  canvasMove(event) {
    if (isButtonDown) {
      arrz.push(1);
      arrx.push(event.changedTouches[0].x);
      arry.push(event.changedTouches[0].y);
    }
    for (var i = 0; i < arrx.length; i++) {
      if (arrz[i] == 0) {
        context.moveTo(arrx[i], arry[i])
      } else {
        context.lineTo(arrx[i], arry[i])
      }
    }
    context.clearRect(0, 0, canvasw, canvash);
    if(this.data.sysType === 'iOS') {
      context.fillStyle = 'rgba(255, 255, 255, 1)';
      context.setStrokeStyle('#444');
    } else {
      context.fillStyle = 'rgba(0, 0, 0, 1)';
      context.setStrokeStyle('#aaa');
    }
    context.setLineWidth(3);
    context.setLineCap('round');
    context.setLineJoin('round');
    context.stroke();
    context.draw(false);
  },
  canvasEnd(event) {
    isButtonDown = false;
  },
  // Clear the canvas cleardraw() {
    arrx = [];
    arry = [];
    arrz = [];
    context.clearRect(0, 0, canvasw, canvash);
    if(this.data.sysType === 'iOS') {
      context.fillStyle = 'rgba(255, 255, 255, 1)';
      context.setStrokeStyle('#444');
    } else {
      context.fillStyle = 'rgba(0, 0, 0, 1)';
      context.setStrokeStyle('#aaa');
    }
    context.draw(true);
  },
  uploadImg() {
    var that = this
    //Generate image// context.draw(true,()=> {
    setTimeout(() => {
      wx.canvasToTempFilePath({
        canvasId: 'canvas',
        //Set the width and height of the output image fileType: 'jpg',
        quality: 1,
        success: function (res) {
          // canvas image address res.tempFilePath
          let imgBase64 = wx.getFileSystemManager().readFileSync(res.tempFilePath, 'base64')
          that.setData({
            imgUrl: res.tempFilePath,
            signBase64: imgBase64
          })
          that.submitSign()
          console.log('imgBase64', 'data:image/jpeg;base64,' + imgBase64)
          // wx.saveImageToPhotosAlbum({
          // filePath: res.tempFilePath,
          // success(res4) { 
          // console.log(res,'Save res4');
          // wx.showToast({
          // title: 'Successfully saved to album',
          // duration: 2000
          // } );
          // }
          // })
        },
        fail: function () {
          wx.showModal({
            title: 'Tips',
            content: 'Canvas failed to generate the image. The current version of WeChat is not supported, please update to the latest version! ',
            showCancel: false
          });
        },
        complete: function () { }
      }, 5000)

    })
    // })
  },
  // Submit signature submitSign() {
    let that = this
    wx.showLoading({
      title: 'Submitting...',
      mask: true
    })
    let type = '1'
    if (that.data.sysType === 'iOS') {
      type = '0'
    } else {
      type = '1'
    }
    wx.$getWxLoginCode(resp => {
      const params = {
        qmbase64: that.data.signBase64,
      
      }
      console.info("params")
      wx.kservice.yyyurl(params, res => {
        wx.hideLoading()
        if (res.statusCode === '200') {
          wx.showModal({
            title: 'Tips',
            content: res.message,
            showCancel: false,
            confirmText: 'Return to home page',
            success(res) {
              if (res.confirm) {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
              }
            }
          })
        } else {
          wx.showModal({
            title: 'Tips',
            content: res.message,
            showCancel: true,
            cancelText: 'Return to home page',
            confirmText: 'Resubmit',
            success: (result) => {
              if (result.cancel) {
                //Cancel the stay wx.reLaunch({
                  url: '/pages/index/index'
                })
              } else if (result.confirm) {
                //Resubmit that.submitSign()
              }
            },
          });
        }
      }, {}, true, true)
    })
  },

  /**
  * Life cycle function--monitor page uninstallation*/
  onUnload: function () {

  },

  /**
   * Page related event processing function - listen to user pull-down action */
  onPullDownRefresh: function () {

  },

  /**
   * The function that handles the bottoming event on the page*/
  onReachBottom: function () {

  },

  /**
   * User clicks on the upper right corner to share*/
  onShareAppMessage: function () {

  }
})

CSS:

.sign-contain {
  display: flex;
  flex-direction:column;
  width: 100%;
  height: 100%;
}
.signName {
  flex: 1;
}
.canvas {
  width: 100%;
  height: 100%;
}
.bg000{
  background-color: #000;
}
.btn-wrap{
  display: block;
  width:100%;
  height: 100rpx;
  margin: 20rpx 0;
  position: relative;
}
.btn-wrap button{
  width: 43%;
}

I would like to recommend a WeChat Mini Program tutorial which is quite popular right now: "WeChat Mini Program Development Tutorial" which has been carefully compiled by the editor. I hope you like it.

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

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 applet implements a simple handwritten signature component
  • 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

<<:  Detailed steps to store emoji expressions in MySQL

>>:  Summary of methods to improve mysql count

Recommend

Best Practices for MySQL Upgrades

MySQL 5.7 adds many new features, such as: Online...

Detailed steps for installing ros2 in docker

Table of contents Main topic 1. Install Docker on...

JavaScript design pattern learning adapter pattern

Table of contents Overview Code Implementation Su...

IE8 provides a good experience: Activities

Today I had a sneak peek at IE8 beta 1 (hereafter...

Sublime Text - Recommended method for setting browser shortcut keys

It is common to view code effects in different br...

How to understand JS function anti-shake and function throttling

Table of contents Overview 1. Function debounce 2...

Introduction to Semantic XHTML Tags

The first point to make is that people can judge t...

Use personalized search engines to find the personalized information you need

Many people now live on the Internet, and searchin...

Jenkins Docker static agent node build process

A static node is fixed on a machine and is starte...

Solution to the problem that Docker cannot stop or delete container services

Preface Today, a developer gave me feedback that ...

Using js to achieve waterfall effect

This article example shares the specific code of ...

MySQL 8.0.22 download, installation and configuration method graphic tutorial

Download and install MySQL 8.0.22 for your refere...

Implementation code for partial refresh of HTML page

Event response refresh: refresh only when request...

Two practical ways to enable proxy in React

Two ways to enable proxy React does not have enca...