<view class="container">
<view class="canvas-container">
<canvas id="signature" canvas-id="signatureCanvas"
bindtouchstart="startDrawing"
bindtouchmove="drawing"
bindtouchend="endDrawing"
></canvas>
</view>
<view class="btn-container">
<button class="btn-clear" bindtap="clearSignature">清空</button>
<button class="btn-save" bindtap="saveSignature">保存</button>
</view>
<view class="image-container">
<image src="{{signatureImage}}" mode="aspectFit"></image>
</view>
</view>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.canvas-container {
width: 300px;
height: 150px;
background-color: #f9f9f9;
margin-bottom: 20px;
border: 1px solid #ccc;
}
.btn-container {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 20px;
}
.btn-clear,
.btn-save {
padding: 10px 20px;
background-color: #4c8efe;
color: #fff;
border: none;
border-radius: 5px;
margin: 0 10px;
}
.image-container {
width: 300px;
height: 150px;
}
Page({
data: {
ctx: null,
drawing: false,
signatureImage: '',
},
onReady: function () {
this.data.ctx = wx.createCanvasContext('signatureCanvas');
},
startDrawing: function (e) {
this.data.ctx.setStrokeStyle('#000000');
this.data.ctx.setLineWidth(3);
this.data.ctx.setLineCap('round');
this.data.ctx.setLineJoin('round');
this.data.ctx.beginPath();
this.data.ctx.moveTo(e.touches[0].x, e.touches[0].y);
this.data.drawing = true;
},
drawing: function (e) {
if (!this.data.drawing) return;
this.data.ctx.lineTo(e.touches[0].x, e.touches[0].y);
this.data.ctx.stroke();
this.data.ctx.draw(true);
},
endDrawing: function () {
this.data.ctx.closePath();
this.data.drawing = false;
},
clearSignature: function () {
this.data.ctx.clearRect(0, 0, 300, 150);
this.data.ctx.draw(true);
this.setData({
signatureImage: '',
});
},
saveSignature: function () {
var _this = this;
wx.canvasToTempFilePath({
canvasId: 'signatureCanvas',
success: function (res) {
_this.setData({
signatureImage: res.tempFilePath,
});
},
fail: function (error) {
console.log('保存签名失败', error);
},
}, _this);
},
});
在上述代码中,我们为签名区域定义了一个
<canvas>
元素,并使用了触摸事件实现绘制功能。清空按钮和保存按钮分别绑定了clearSignature
和saveSignature
函数来清空签名和保存签名。 当点击保存按钮后,使用wx.canvasToTempFilePath
将签名区域内容保存为图片,并将该图片的临时路径绑定到signatureImage
数据上,从而在<image>
元素中展示签名图片。 请注意,在实际开发中,你可能需要根据项目的需求对样式进行调整,并根据需要处理更多的事件逻辑或数据管理操作。以上代码仅提供了一个基本的电子签名示例,你可以根据自己的需求进行扩展和优化。