美文网首页
小程序canvas实现签名

小程序canvas实现签名

作者: 焚心123 | 来源:发表于2022-08-03 15:46 被阅读0次
这里使用获取canvas节点实现的,最新的api,小程序将canvas中的api变成了h5中使用canvas的那中写法,可以参考h5中canvas的用法https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/fillStyle
  • 这里实现是使用的mini-smooth-signature插件,可以在npm官网中进行搜索到
  • 首先使用canvas标签,下面的两个属性是必须的,要不然获取节点,获取不到
<canvas type="2d" id="myCanvas"></canvas>
  • 具体的wxml代码
 <view class="canvas-sign">
  
    <canvas
      type="2d"
      id="signature1"
      class="signature1"
      style="width:{{width}}px;height:{{height}}px;"
      disable-scroll="{{true}}"
      bindtouchstart="handleTouchStart1"
      bindtouchmove="handleTouchMove1"
      bindtouchcancel="handleTouchEnd1"
      bindtouchend="handleTouchEnd1"
    ></canvas>
    <view class="actions1">
      <button bindtap="handleClear1">
        清除
      </button>
      <button bindtap="handleUndo1">
        撤销
      </button>
      <button bindtap="handlePreview1">
       生成图片
      </button>
      <button bindtap="handleColor1">
        修改颜色
      </button>

    </view>
    
  </view>
  • wxss
/* 样例1 */
.container1 {
  text-align: center;
}
.signature1 {
  margin: 25px auto;
  border: 2rpx solid #eee;
}
.actions1 {
  margin-top: 20px;
  text-align: center;
}
.actions1 button {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
}
  • js canvas的宽度,高度是必填的,否则也获取不到节点信息
import Signature  from '../../utils/index'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    width: {
      type: Number,
      value: 400
    },
    height:{
      type: Number,
      value: 728
    },
    color:{
      type:String,
      value:'000'
    },
    bgColor:{
      type:String,
      value:'#eee'
    },
    textList:{
      type:Array,
      value:[]
    },
    pixelRatio:{
      type: Number,
      value: 1
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
  
  },
  pageLifetimes:{
    show(){
      this.initCanvas()
    },
    
  },
  /**
   * 组件的方法列表
   */
  methods: {
    //初始化函数
    initCanvas: function () {
      const query = wx.createSelectorQuery().in(this)
      query.select('#signature1').fields({ node: true, size: true }).exec(res=>{
          console.log(res,'节点信息');
          const canvas = res[0].node
          const ctx = canvas.getContext('2d')
          canvas.width = +this.data.width * +this.data.pixelRatio
          canvas.height = +this.data.height * +this.data.pixelRatio;
          this.signature1 = new Signature(ctx, {
              width: +this.data.width,
              height: +this.data.height,
              scale: +this.data.pixelRatio,
              textList: this.data.textList,
              // textList:[//上下添加文本
              //   {x:0,y:20,text:'hello',center:'start',color: this.data.color},
              //   {x:200,y:200,text:'底部1111',center:'start',color: this.data.color}
              // ],
              color:this.data.color,
              // bgColor: this.data.bgColor,//背景色跟添加文本有冲突,两者取其一
              toDataURL: (type, quality) => canvas.toDataURL(type, quality),
              requestAnimationFrame: (fn) => canvas.requestAnimationFrame(fn),
              getImagePath: () => new Promise((resolve, reject) => {
                const img = canvas.createImage();
                img.onerror = reject;
                img.onload = () => resolve(img);
                img.src = canvas.toDataURL();
              })
            })
            
      })
      
    },
    //开始
    handleTouchStart1(e) {
      const pos = e.touches[0];
      this.signature1.onDrawStart(pos.x, pos.y);
    },
    // 移动
    handleTouchMove1(e) {
      const pos = e.touches[0];
      this.signature1.onDrawMove(pos.x, pos.y);
    },
    // 结束
    handleTouchEnd1() {
      this.signature1.onDrawEnd();
    },
    //清空
    handleClear1() {
      this.signature1.clear();
    },
    //撤销
    handleUndo1() {
      this.signature1.undo();
    },
    //修改颜色
    handleColor1() {
      this.signature1.color = '#' + Math.random().toString(16).slice(-6);
    },
    //确认,签名后生成图片
    handlePreview1() {
      if (this.signature1.isEmpty()) {
        wx.showToast({ icon: 'none', title: '未签名' });
        return;
      }
      const dataURL = this.signature1.toDataURL();
      this.base64ToPath(dataURL).then(url => {
        // wx.compressImage({

        // })
        url&& this.triggerEvent("signUrl",{url})
        
      });
    },
    // base64转本地
    base64ToPath(dataURL) {
        return new Promise((resolve, reject) => {
        const data = wx.base64ToArrayBuffer(dataURL.replace(/^data:image\/\w+;base64,/, ""));
        const filePath = `${wx.env.USER_DATA_PATH}/${Math.random().toString(32).slice(2)}.png`;
        wx.getFileSystemManager().writeFile({
            filePath,
            data,
            encoding: 'base64',
            success: () => resolve(filePath),
            fail: reject,
        });
      })
    },

  }
})

  • 在使用组件进行传参的时候,需要加个条件判断下,否则渲染太快导致页面的布局有问题
  • 使用组件的js页面
// packageH/pages/signature/signature.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    width1: '',
    height1: '',
    pixelRatio: ''
  },
  signUrl(e){
      console.log(e);
    if(e.detail.url){
        wx.setStorageSync('canvasSign', e.detail.url)
        wx.navigateBack({
          delta: 1,
        })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const { windowWidth, windowHeight, pixelRatio  } = wx.getSystemInfoSync()
        
    this.setData({
        width1: windowWidth-14,
        height1: windowHeight-140,
        pixelRatio
    })
   
  },
})
  • 使用组件的wxml
<view class="canvas-sign">
<view class="title">
  请手写签名:
</view>
<!--  这里需要加个条件判断下,否则组件的渲染有问题-->
<block wx:if="{{width1}}">
  <canvas-sign bind:signUrl="signUrl"  width="{{width1}}" height="{{height1}}" pixelRatio="{{pixelRatio}}"></canvas-sign>
</block>
</view>

  • 使用组件的json中进行引入
{
  "usingComponents": {
    "canvas-sign":"../../../components/canvasSign/canvasSign"
  },
  "navigationBarTitleText": "签名"
}
  • 不想使用插件,也可以自己使用canvas进行写,很简单的,具体可以参考我的另一篇h5使用canvas进行绘制的这篇文章
小程序中使用canvas写的进行适配
  • 标题换行
  // 文字换行
  drawtext(ctx,t,x,y,w){
    //参数说明
    t = t.split('');
    let tL = Math.ceil(t.length / 16);
  
    console.log(tL,'几行',t,t.length);
    for(let i = 0; i < tL ; i++){
      y = i > 0 ? y+30 : y
      ctx.fillText( t.join('').substr(i*16,16),x,y,w);//每行字体y坐标间隔20
      console.log(' arr.slice(i*16,16)', t.join('').substr(i*16,16),y,t);
    }
    return y
  },
  • 标题下面的y坐标使用上面的函数导出的y坐标进行加一个固定值就可以
  • canvas的宽度使用获取屏幕的宽度就可以
  • 将rpx单位转px
const { windowWidth, windowHeight, pixelRatio  } = wx.getSystemInfoSync()
 const px = (rpx)=>rpx / 375 * windowWidth 

注意:在使用canvas生成图片之后,图片的路径是base64的格式,上面有使用 wx.getFileSystemManager().writeFile这个api进行转为本地路径的图片格式,但是这个有的用户手机上会有问题,微信环境中会报错,提示storage超出限制,最后没有办法,直接将base64传递给后台,让后台进行转化(可能你会问,为啥不能直接base64的形式上传图片,这个是wx.upload这个api的限制,需要本地路径,不支持base64),或者使用 wx.canvasToTempFilePath这个api,最新的canvas - api用不了这个

相关文章

网友评论

      本文标题:小程序canvas实现签名

      本文链接:https://www.haomeiwen.com/subject/nsurwrtx.html