微信小程序 canvas 实现签字并转为img

用的是canvas 最后转为base64格式的图片文件

Page({

  data: {
    canvas: null,
    ctx: null,
    alreadyDraw: false,
    src: null,
    width: 0,
    height: 0
  },

  onReady() {
    const query = wx.createSelectorQuery()
    query.select('#myCanvas')
      .fields({ node: true, size: true })
      .exec((res) => {
        console.log(res)
        // Canvas 对象
        const canvas = res[0].node
        // 渲染上下文
        const ctx = canvas.getContext('2d')
        console.log(canvas, ctx)
        // Canvas 画布的实际绘制宽高
        const width = res[0].width
        const height = res[0].height
        // 初始化画布大小
        const dpr = wx.getSystemInfoSync().pixelRatio
        canvas.width = width * dpr
        canvas.height = height * dpr
        ctx.scale(dpr, dpr)

        ctx.lineWidth = 3
        ctx.lineCap = 'round'
        this.setData({
          canvas,
          ctx,
          width,
          height
        })
      })
  },

  /** 开始触摸 */
  touchStart(e) {
    console.log(e)
    let ctx = this.data.ctx
    ctx.moveTo(e.touches[0].x, e.touches[0].y);
    this.setData({
      ctx,
    });
  },

  /** 移动 */
  touchMove(e) {
    var ctx = this.data.ctx;
    const x = e.touches[0].x
    const y = e.touches[0].y
    ctx.lineTo(x, y);
    ctx.stroke();
    ctx.moveTo(x, y);
    if (!this.data.alreadyDraw) {
      this.setData({
        alreadyDraw: true, 
      });
    }
  },

  /** 重新签名 */
  reSign() {
    const { ctx, width, height } = this.data
    ctx.clearRect(0, 0, width, height)
    this.setData({
      ctx,
      src: null,
      alreadyDraw: false,
    })
  },

  /** 完成签名 */
  signOk() {
    if (!this.data.alreadyDraw) {
      wx.showToast({
        title: '请先签字',
        icon: 'none'
      })
    } else {
      var canvas = this.data.canvas;
      const img = canvas.toDataURL()
      // console.log(img)
      this.setData({
        src: img
      })
    }
  },
})

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值