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

The process of installing SVN on Ubuntu 16.04.5LTS

This article briefly introduces the process of se...

JS cross-domain XML--with AS URLLoader

Recently, I received a requirement for function ex...

Solve the black screen problem after VMware installs Linux system and starts

1. Installation environment 1. HUAWEI mate x cpu ...

Vue+echart realizes double column chart

This article shares the specific code of vue+echa...

How to install Tomcat-8.5.39 on centos7.6

Here is how to install Tomcat-8.5.39 on centos7.6...

Detailed tutorial on installing Mysql5.7.19 on Centos7 under Linux

1. Download MySQL URL: https://dev.mysql.com/down...

Linux automatic login example explanation

There are many scripts on the Internet that use e...

Vue implements setting multiple countdowns at the same time

This article example shares the specific code of ...

How to install OpenSuse on virtualbox

The virtual machine is installed on the host mach...

Detailed explanation of top command output in Linux

Preface I believe everyone has used the top comma...

How to Dockerize a Python Django Application

Docker is an open source project that provides an...

In-depth understanding of MySQL global locks and table locks

Preface According to the scope of locking, locks ...