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

相关推荐
fakaifa2 小时前
八戒农场小程序V2最新源码
小程序·uni-app·php·生活·开源软件
包淼淼2 小时前
微信小程序自定义navigationBar顶部导航栏(背景图片)适配所有机型,使用tdesign-miniprogram t-navbar设置背景图片
微信小程序·小程序·tdesign
2401_844137952 小时前
JAVA同城生活新引擎外卖跑腿团购到店服务多合一高效系统小程序源码
微信·微信小程序·小程序·生活·微信公众平台·微信开放平台
哈尔滨财富通科技3 小时前
财富通公司开发维修售后小程序,解决售后维修问题
大数据·小程序·云计算·售后小程序·哈尔滨小程序
我非夏日3 小时前
小程序开发设计-第一个小程序:注册小程序开发账号②
小程序
骆晨学长3 小时前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
风等雨归期6 小时前
【python】【绘制小程序】动态爱心绘制
开发语言·python·小程序
李宥小哥7 小时前
微信小程序07-开发进阶
微信小程序·小程序·notepad++
艾小逗8 小时前
uniapp快速入门教程,内容来源于官方文档,仅仅记录快速入门需要了解到的知识点
小程序·uni-app·app·es6
程序员阿龙8 小时前
【2025】儿童疫苗接种预约小程序(源码+文档+解答)
小程序·毕业设计·小程序开发·预约小程序·疫苗管理小程序·出勤数据分析·智能考勤