canvas设置签名区域

142 阅读1分钟

html页面布局:

    <view class="weui-dialog" style="width:100%">
      <view class="weui-dialog__title" style="margin-top: 20rpx;">
        <view>签字区</view>
      </view>
      <canvas disable-scroll="false" style="width:100%;height: {{cardHeight}}px;{{display}}" canvas-id="firstCanvas" class="firstCanvas" bindtouchstart="bindtouchstart" bindtouchmove="bindtouchmove"></canvas>
      <view class="weui-dialog__ft">
        <view style="color:#E7161B" class="weui-dialog__btn" bindtap="closeTips">取消</view>
        <view style="color:#E7161B" class="weui-dialog__btn" bindtap="clear">清除</view>
        <view style="color:#E7161B" class="weui-dialog__btn" bindtap="export">确认</view>
      </view>
    </view>

获取高度:

onLoad: function (options) {
    let _this = this;

    // 这里需要获取多个元素的高度,所以用的是selectAll
    wx.createSelectorQuery().selectAll('.firstCanvas').boundingClientRect().exec(function (res) {
      _this.setData({
        tabContHeight: res[0][0].height,
        tabContWidth: res[0][0].widht,
      })
    })

    var windowHeight = wx.getSystemInfoSync().windowHeight
    var windowWidth = wx.getSystemInfoSync().windowWidth

    this.setData({
      windowHeight: windowHeight,
      windowWidth: windowWidth,
      cardHeight: windowHeight - this.data.height - 300,
    })

  },

确认签字保留canvas配置

// 确认签字
  export () {
    let that = this;
    that.data.context.draw(true, wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 300,
      height: 365,
      fileType: 'png',
      canvasId: 'firstCanvas',
      success(res) {
        setTimeout(() => {
          const {
            tempFilePath
          } = res;
          if (that.data.changedTouchesX !== "" || that.data.changedTouchesY !== "") {
            // 合并图片
            that.generateProtocol(tempFilePath);
          } else {
            wx.showToast({
              title: '请签字!',
              icon: 'none',
            })
          }
          that.setData({
            imgUrl: tempFilePath,
          })
        }, 500);
      },
      fail() {
        wx.showToast({
          title: '签字失败',
          icon: 'none',
          duration: 2000
        })
      }
    }))
  },

记录开始点位及移动过程

  /**记录开始点 */
  bindtouchstart: function (e) {
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
  },

  /**记录移动点,刷新绘制 */
  bindtouchmove: function (e) {
    this.data.context.lineTo(e.changedTouches[0].x, e.changedTouches[0].y);
    this.data.context.stroke();
    this.data.context.draw(true);
    this.data.context.moveTo(e.changedTouches[0].x, e.changedTouches[0].y);
    this.setData({
      changedTouchesX: e.changedTouches[0].x,
      changedTouchesY: e.changedTouches[0].y
    });
  },

清空画布

  /**清空画布 */
  clear: function () {
    this.data.context.draw();
    this.data.context.setStrokeStyle('blue')
    this.data.context.setFillStyle('white')
    this.data.context.setLineWidth(2)
  },