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

相关推荐
2501_915918419 小时前
如何在iPad上找到并打开文件夹的完整指南
android·ios·小程序·uni-app·iphone·webview·ipad
shejizuopin10 小时前
基于Spring Boot+小程序的非遗科普平台设计与实现(毕业论文)
spring boot·后端·小程序·毕业设计·论文·毕业论文·非遗科普平台设计与实现
StarChainTech13 小时前
一站式租车平台革新:从信用免押到全流程可视化管理的技术实践
大数据·人工智能·微信小程序·小程序·软件需求
CHU72903515 小时前
一番赏盲盒抽卡机小程序:探索惊喜与互动的多元功能体验
小程序
换日线°16 小时前
微信小程序对接位置服务(腾讯、高德)完成路径规划
前端·微信小程序·vue
2501_9159184116 小时前
Wireshark、Fiddler、Charles抓包工具详细使用指南
android·ios·小程序·https·uni-app·iphone·webview
苏苏哇哈哈17 小时前
微信小程序实现仿腾讯视频小程序首页圆角扩散轮播组件
微信小程序·小程序·轮播图
code袁17 小时前
基于微信小程序的宿舍维修小程序的设计与实现
微信小程序·小程序·毕业设计·springboot·notepad++·宿舍维修小程序
说私域17 小时前
AI智能客服S2B2C商城小程序在客户服务场景中的应用与价值——以顾客反馈处理为例
人工智能·小程序·流量运营·私域运营
黄菊华老师1 天前
微信小程序毕业设计:渔具商城小程序毕设源码作品和开题报告
微信小程序·小程序·课程设计·渔具商城小程序