微信小程序使用 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 ;

相关推荐
苹果电脑的鑫鑫4 小时前
微信小程序后端传入图片比容器大导致变形解决方法
微信小程序·小程序
curdcv_po6 小时前
我接入了微信小说小程序官方阅读器
前端·微信小程序
微爱帮监所写信寄信8 小时前
微爱帮监狱写信寄信小程序针对互联网黑灰产攻击防护体系
小程序·负载均衡·信息与通信·安全架构·安全防护·监狱寄信
Bug生活204810 小时前
五年断更,AI助我半天复活小程序
前端·微信小程序·ai编程
2501_9159184110 小时前
iOS 开发中证书创建与管理中的常见问题
android·ios·小程序·https·uni-app·iphone·webview
00后程序员张10 小时前
IOScer 开发环境证书包括哪些,证书、描述文件与 App ID 的协同管理实践
android·ios·小程序·https·uni-app·iphone·webview
沃夫上校11 小时前
微信模板消息不能长期订阅?可以试试“用工关系“
微信小程序
采云 AI11 小时前
小程序订单接单超时时间功能解释
服务器·小程序·apache
趁着年轻吃点苦12 小时前
小程序主包体积优化 - 路径迁移修复实战
小程序
Tancenter13 小时前
支付宝小程序的用户登录/注册流程
小程序·登录·注册·支付宝