适用于uniapp和小程序使用canvas完成的手写签名
在statement.wxml页面上使用canvas组件
<canvas
id="canvas"
class="write canvas"
type="2d"
disable-scroll="true"
bindtouchstart="handleTouchStart"
bindtouchmove="handleTouchMove"
bindtouchend="handleTouchEnd"
bindtouchcancel="handleTouchCancel"
></canvas>
在statement.js里面具体使用:
const app=getApp()
Page({
/**
* 页面的初始数据
*/
data: {
//签名属性
canvas: '',
canvasWidth: 0,
canvasHeight: 0,
canvasContext: '',
drawStartX: 0,
drawStartY: 0,
draw: false, //判断是否签名
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
confirm() {
if(this.data.draw) { //已签名
this.uploadCanvasImg()
}else { //给出提示
wx.showToast({
title: '请签名',
icon: 'none'
})
}
},
//上传图片
uploadCanvasImg() {
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 343,
height: 160,
destWidth: 343,
destHeight: 160,
canvas: this.data.canvas,
fileType: 'png',
quality: 1, //图片质量
success(res) {
wx.uploadFile({
filePath: res.tempFilePath,
name: 'file',
url: 'xxxxxxxxxx', //请替换成自己的上传地址
header: {
"content-type":"multipart/form-data"
},
success: function(t) {
var a = JSON.parse(t.data);
wx.showToast({
title: '上传成功',
icon: 'none',
duration: 1000
})
setTimeout(function() {
wx.navigateBack({
delta: 1,
})
},1000)
wx.hideLoading();
}
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that=this;
//新版本的获取canvas对象
const query = wx.createSelectorQuery()
query.select('#canvas')
.fields({ node: true, size: true })
.exec((res) => {
const canvas = res[0].node
const ctx = canvas.getContext('2d')
this.setData({
canvas: canvas,
canvasContext: ctx,
canvasWidth: res[0].width,
canvasHeight: res[0].height
})
const dpr = wx.getSystemInfoSync().pixelRatio
this.data.canvas.width = res[0].width * dpr
this.data.canvas.height = res[0].height * dpr
this.data.canvasContext.scale(dpr, dpr)
this.data.canvasContext.strokeStyle = '#2A2A2A';
this.data.canvasContext.lineWidth = 4;
this.data.canvasContext.lineCap = 'round';
})
//旧版本的获取canvas对象
},
//重新签名
reset() {
this.clearCanvas()
},
/* 触摸开始 */
handleTouchStart(e) {
this.setData({
drawStartX: e.changedTouches[0].x,
drawStartY: e.changedTouches[0].y
})
this.data.canvasContext.beginPath();
},
/* 触摸移动 */
handleTouchMove(e) {
/* 记录当前位置 */
const tempX = e.changedTouches[0].x;
const tempY = e.changedTouches[0].y;
/* 画线 */
this.data.canvasContext.moveTo(this.data.drawStartX, this.data.drawStartY);
this.data.canvasContext.lineTo(tempX, tempY);
this.data.canvasContext.stroke();
/* 重新记录起始位置 */
this.setData({
drawStartX: tempX,
drawStartY: tempY
})
},
/* 触摸结束 */
handleTouchEnd(e) {
this.data.canvasContext.save();
//记录状态
this.setData({
draw: true
})
},
/* 触摸取消 */
handleTouchCancel(e) {
this.data.canvasContext.save();
},
/* 清空画布 */
clearCanvas() {
this.data.canvasContext.clearRect(0, 0, this.data.canvasWidth, this.data.canvasHeight);
this.setData({
draw: false
})
},
})