微信小程序使用Canvas实现签字绘制功能
发布于 1 年前 作者 hxiong 4798 次浏览 来自 分享

微信小程序使用Canvas实现签字绘制功能

1、效果图

2、代码仓库

https://gitee.com/synctimes/canvas-sign/tree/master

3、部分代码演示

Page({
  data: {
    context1null,
    hasDrawfalse//默认没有画
    srcnull
  },
  onLoadfunction () {
    var self = this;

    var context1 = wx.createCanvasContext('handWriting1');
    context1.setStrokeStyle("#000000")
    context1.setLineWidth(3);
    this.setData({
      context1: context1,
    })
  },
  touchstart1function (e{
    var context1 = this.data.context1;
    context1.moveTo(e.touches[0].x, e.touches[0].y);
    this.setData({
      context1: context1,
      hasDrawtrue//要签字了
    });
  },
  touchmove1function (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);
  },
  reSign1function () //重新画
    var self = this;
    var context1 = self.data.context1;
    context1.draw(); //清空画布
    self.setData({
      hasDrawfalse//没有画
      srcnull
    });

    self.ajaxLoading = false;

  },
  sign1okfunction () {

    var self = this;

    if (!self.data.hasDraw) {
      console.log("签字是空白的 没有签字")
      return
    }
    var context1 = self.data.context1;
    context1.draw(true, wx.canvasToTempFilePath({
      canvasId'handWriting1',
      success(res) {
        console.log(res.tempFilePath) //得到了图片下面自己写上传吧
        self.setData({
          src: res.tempFilePath
        })
    

        const fs = wx.getFileSystemManager();
        fs.getFileInfo({
          filePath: res.tempFilePath,
          success(result) {
            console.log("getFileInfo result=>", result)

            res.size = result.size;

          },
          fail(err) {

          }
        })
      }
    }))
  },

});
<view class="g-doc">
  <view class="g-bd">
    <view class="paper">
      <canvas class="handWriting" disable-scroll="true" bindtouchstart="touchstart1" bindtouchmove="touchmove1" canvas-id="handWriting1">
      </canvas>
    </view>
  </view>
  <view class="g-ft">
    <view class="weui-flex">
      <view class="weui-flex__item" bindtap="reSign1">
        <view class="f-ins2">
          重新签字
        </view>
      </view>
      <view class="weui-flex__item" bindtap="sign1ok">
        <view class="f-ins1">
          提交
        </view>
      </view>
    </view>
    <view class="iphonex-env-constant"></view>
  </view>
</view>

4、相关参考文献

https://developers.weixin.qq.com/miniprogram/dev/component/canvas.html

https://juejin.cn/post/6991670574200127495

5、使用问题描述

签字三 在真机安卓手机下,存在无法绘制问题。

签字二,实际使用场景中,因为我是在 列表页-列表详情页-表单页-签字页。存在页面较多层级的状态下,会出现卡顿,iPhone越画往后会感觉卡顿明显。而页面栈只有一层时,则很流畅。

1 回复
大佬,createCanvasContext方法不是弃用了吗,怎么替代一下
回到顶部