<canvas type='2d' id='signatureCanvas' style='background-color:#fff;width: 100%; height: 200px;'
bindtouchstart='touchStart'
bindtouchmove='touchMove' bindtouchend='touchEnd' bindtouchcancel='touchEnd'
disable-scroll='true'></canvas>
<gc-button width='100' bindclick='clearCanvas' text='清空'></gc-button>
<gc-button width='100' type='primary' bindclick='saveSignature' text='保存签字'
style='margin-left:10px'></gc-button>
Page({
data: {
isDrawing: false,
hasDraw: false,
lastPoint: { x: 0, y: 0 },
},
// 页面加载完成,初始化画布
onLoad: function() {
wx.createSelectorQuery()
.select('#signatureCanvas')
.node(({ node: canvas }) => {
const context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width, canvas.height)
})
.exec()
},
touchStart: function(e) {
console.log('touchStart1')
this.setData({ isDrawing: true })
this.setData({ lastPoint: { x: e.touches[0].x, y: e.touches[0].y } })
console.log('touchStart2')
},
touchMove: function(e) {
console.log('touchMove1')
if (!this.data.isDrawing) return
this.setData({ hasDraw: true })
this.draw(e.touches[0].x, e.touches[0].y)
console.log('touchMove2')
},
touchEnd: function() {
console.log('touchEnd1')
this.setData({ isDrawing: false })
console.log('touchEnd2')
},
draw: function(x, y) {
console.log('draw')
const lastPoint = this.data.lastPoint
wx.createSelectorQuery()
.select('#signatureCanvas')
.node(({ node: canvas }) => {
const context = canvas.getContext('2d')
context.beginPath()
context.moveTo(lastPoint.x, lastPoint.y)
context.lineTo(x, y)
context.stroke()
this.setData({ lastPoint: { x, y } })
}) .exec()
},
clearCanvas: function() {
wx.createSelectorQuery()
.select('#signatureCanvas')
.node(({ node: canvas }) => {
const context = canvas.getContext('2d')
context.clearRect(0, 0, canvas.width, canvas.height)
this.setData({ isDrawing: false, hasDraw: false })
}).exec()
},
saveSignature: function() {
if (!this.data.hasDraw) {
console.log('签字是空白的 没有签字')
}
wx.createSelectorQuery()
.select('#signatureCanvas') // 在 WXML 中填入的 id
.node(({ node: canvas }) => {
// wx.canvasToTempFilePath({
// canvas,
// success: (res) => {
// // 在这里可以将res.tempFilePath上传到服务器保存签字数据
// wx.uploadFile({
// url: 'your_server_url', // 后端接口地址
// filePath: res.tempFilePath,
// name: 'signature',
// success: (uploadRes) => {
// // 文件上传成功,可以在这里处理返回的数据
// console.log(uploadRes);
// },
// });
// },
// });
}).exec()
},
})
https://developers.weixin.qq.com/community/develop/doc/0006aa8c0dcaf8548dfbe8c455bc14?_at=1700033135679
问题已知