小程序使用canvas 2D实现签字效果

效果如下:
在这里插入图片描述
请结合小程序官方文档进行解读
wxml:

<view>
  <view>请在下方签字:</view>
  <canvas id="myCanvas"
  type="2d"
  style="border:1px solid #d3d3d3;"
  bindtouchstart="start"
  bindtouchmove="move"
  bindtouchend="end"/>
 <view>
  <button  bind:tap="clearCan">清除</button>
  <button type="submit" bind:tap="submitCan">保存</button>
  <van-image width="100" height="100" model:src="{{canvanImg}}" />
 </view>

js:

/**
   * 页面的初始数据
   */
  data: {
    canvas:null,
    CanvasCote:null,
    canvanImg:"",
  },
  //触摸开始
   start (e) {
    this.data.CanvasCote.beginPath()
    this.data.CanvasCote.moveTo(e.touches[0].x,e.touches[0].y)
  },
  //触摸移动
  move (e) {
    this.data.CanvasCote.lineTo(e.touches[0].x, e.touches[0].y)
    this.data.CanvasCote.stroke()//将上下文绘制到canvas中
  },
  //触摸结束
  end (e) {
    this.data.CanvasCote.closePath()
  },
  //清除画布内容
  clearCan(){
    this.data.CanvasCote.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height)
    this.setData({
      canvanImg:""
    })
  },
  //点击保存生成图片
  submitCan(){
    this.setData({
      canvanImg:this.data.canvas.toDataURL("image/png")
    })
    console.log(this.data.canvas.toDataURL("image/png"))
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    const query = wx.createSelectorQuery()
    query.select('#myCanvas').node().exec((res) => {
      that.setData({
        canvas: res[0].node,
        CanvasCote: res[0].node.getContext('2d')
      })
      let ctx = that.data.CanvasCote;
      ctx.fillStyle = "#fff"
      ctx.fillRect(0, 0, that.data.canvas.width, that.data.canvas.height);
      ctx.strokeStyle='black'
      ctx.lineCap = 'round'; // 线条末端添加圆形线帽,减少线条的生硬感
      ctx.lineJoin = 'round'; // 线条交汇时为原型边角
      // 利用阴影,消除锯齿
      ctx.shadowBlur = 1;
      ctx.shadowColor = '#000';
    })
  },

如有任何问题,请留言。

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值