微信小程序使用 canvas 2d 实现签字板组件

本文是在微信小程序中使用 canvas 2d 来实现签字板功能;

效果图:
请添加图片描述
代码:
1、wxml

<view>
  <canvas 
  id="canvas"
  type="2d"
  bindtouchstart="start"
  bindtouchmove="move"
  bindtouchend="end"
  style="border: 1px solid #ccc; width:100%; height:800rpx"
  ></canvas>
  <view style="display: flex;">
    <button bindtap="clear">清除</button>
    <button bindtap="save">保存</button>
  </view>
  <image src="{{canvanImg}}"></image>
</view>

2、js

Component({
  properties: {

  },
  data: {
    canvas:null,
    canvanImg:"",
    ctx:null
  },
  lifetimes:{
    ready(){
      let that = this;
      wx.createSelectorQuery().in(this)
      .select("#canvas")
      .fields({
        node:true,
        size:true
      }).exec((res)=>{
        let canvas = res[0].node;
        let ctx = canvas.getContext("2d");
        let dpr = wx.getSystemInfoSync().pixelRatio;
        canvas.width = res[0].width * dpr;
        canvas.height = res[0].height * dpr;
        ctx.fillStyle = "#fff";
        // 利用阴影,消除锯齿
        ctx.shadowBlur = 1;
        ctx.shadowColor = '#000';
        ctx.scale(dpr, dpr)
        that.setData({
          canvas,
          ctx
        })
      })
    }
  },
  methods: {
    //触摸开始
    start (e) {
      this.data.ctx.beginPath()
      this.data.ctx.moveTo(e.touches[0].x,e.touches[0].y)
    },
    //触摸移动
    move (e) {
      this.data.ctx.lineTo(e.touches[0].x, e.touches[0].y)
      this.data.ctx.stroke()//将上下文绘制到canvas中
    },
    //触摸结束
    end (e) {
      this.data.ctx.closePath()
    },
    //清除画布内容
    clear(){
      this.data.ctx.clearRect(0, 0,this.data.canvas.width, this.data.canvas.height)
      this.setData({
          canvanImg:""
      })
    },
    //点击保存生成图片
    save(){
      this.setData({
          canvanImg:this.data.canvas.toDataURL("image/png")
      })
    },
  }
})

3、总结
canvas 的宽度和高度可以写死,也可以根据当前可是区域动态计算;需要注意的是 res[0].node 的宽度和高度的计算是当前 canvas 元素上的宽度和高度乘设备的 pixelRatio ;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值