小程序canvas签字功能

WXML

  <view class="qianzi">
    <view class="paper">
      <canvas class="handWriting" disable-scroll="true" bindtouchstart="touchstart1" bindtouchmove="touchmove1"
        canvas-id="handWriting1">
      </canvas>
    </view>
    <view class="signBtn">
      <button class="btn1" size=""  bindtap="sign1ok">完成签字</button>
      <button class="btn2" size="" bindtap="reSign1">清除签名</button>
    </view>
  </view>

<view class="image" hidden="{{src?false:true}}">
   <image src="{{src}}"></image>
</view>

JS

data: {
    optionsTaskid: '', //接收到的任务id
    orderKey: '',
    context1: null,
    hasDraw: false, //默认没有画
    src: null,
  },
  
touchstart1: function (e) { var context1 = this.data.context1; context1.moveTo(e.touches[0].x, e.touches[0].y); this.setData({ context1: context1, hasDraw: true, //要签字了 }); }, touchmove1: function (e) { var x = e.touches[0].x; var y = e.touches[0].y; var context1 = this.data.context1; context1.setLineWidth(3); context1.lineTo(x, y); context1.stroke(); context1.setLineCap('round'); context1.draw(true); context1.moveTo(x, y); }, reSign1: function () { //重新画 var that = this; var context1 = that.data.context1; context1.draw(); //清空画布 that.setData({ hasDraw: false, //没有画 src: null }); },
  sign1ok: function () {
    var that = this;
    if (!that.data.hasDraw) {
      return app.Tips({
        title: "您还未签名"
      })
    };
  
      var context1 = that.data.context1;
      context1.draw(true, wx.canvasToTempFilePath({
        canvasId: 'handWriting1',
        success(res) {
          console.log("res:", res)
          console.log(res.tempFilePath) //得到了图片下面自己写上传吧
          let Url = getApp().globalData.url,
            header = HEADER;
          console.log("Url:", Url)
          if (getApp().globalData.token) header[TOKENNAME] = 'Bearer ' + getApp().globalData.token;
          wx.uploadFile({
            url: Url + "/api/task/upload/contract",
            filePath: res.tempFilePath,
            name: "file",
            formData: {
              file: "image",
              key: that.data.orderKey
            },
            header: {
              "Content-Type": "multipart/form-data",
              [TOKENNAME]: 'Bearer ' + getApp().globalData.token
            },
            success: function (result) {
              console.log(result)
              var data = JSON.parse(result.data)
              if (data.status == 200) {
                app.Tips({
                  title: data.msg
                });
                setTimeout(function () {
                  wx.redirectTo({
                    url: '/pages/shouerlige/taskOrder_pay/index?key=' + that.data.orderKey + "&taskid=" + that.data.optionsTaskid,
                  })
                }, 1200)
              }else{
                 return app.Tips({title:data.msg})
              }
            },
            fail:function(err){
            }
          })
        }
      }))
  },
 
原文地址:https://www.cnblogs.com/liuqingxia/p/15719192.html