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

相关推荐
V+zmm1013441 分钟前
自驾游拼团小程序的设计与实现(ssm论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
寰宇软件2 小时前
PHP房屋出租出售高效预约系统小程序源码
前端·小程序·uni-app·vue·php
说私域4 小时前
利用开源AI智能名片2+1链动模式S2B2C商城小程序构建企业私域流量池的策略与实践
大数据·人工智能·小程序·开源
黑马源码库miui520866 小时前
挪车小程序挪车二维码php+uniapp
微信小程序·小程序·微信公众平台
盛夏绽放16 小时前
微信小程序地图map全方位解析
微信小程序·小程序
初尘屿风18 小时前
基于微信小程序的电影院订票选座系统的设计与实现,SSM+Vue+毕业论文+开题报告+任务书+指导搭建视频
vue.js·微信小程序·小程序
paterWang19 小时前
基于SpringBoot的驾校报名小程序系统设计与实现(源码+文档)
spring boot·后端·小程序
EasyNVR21 小时前
EasyRTC:全平台支持与自研算法驱动的智能音视频通讯解决方案
运维·服务器·小程序·音视频·webrtc·p2p·智能硬件
韩召华1 天前
微信小程序(uni)+蓝牙连接+Xprint打印机实现打印功能
微信小程序·小程序·notepad++
韩召华1 天前
微信小程序实现拉卡拉支付
微信小程序·小程序