uniapp 手写电子签名
时间: 2025-03-05 15:44:29 浏览: 80
### 实现手写电子签名功能
在 UniApp 开发环境中,为了实现在不同平台上一致的手写电子签名功能,可以利用 `<canvas>` 组件来创建一个用于绘制用户签名的空间。此方法适用于 H5 网页、微信小程序等多个平台,并能很好地处理跨平台差异[^1]。
下面是一个简单的例子展示如何设置 `canvas` 来允许用户在其上书写自己的名字:
```html
<template>
<view class="signature-pad">
<!-- 定义画布 -->
<canvas type="2d" id="myCanvas"></canvas>
<!-- 控制按钮 -->
<button @click="clearSignature">清除</button>
<button @click="saveSignatureAsImage">保存为图片</button>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null, // canvas 上下文对象
isDrawing: false,
lastX: 0,
lastY: 0
}
},
mounted() {
const query = uni.createSelectorQuery().in(this);
query.select('#myCanvas').fields({node: true, size: true}).exec((res) => {
this.ctx = res[0].getContext('2d');
// 设置画笔属性
this.ctx.lineWidth = 2;
this.ctx.lineCap = 'round';
this.ctx.strokeStyle = '#000';
// 添加触摸事件监听器
res[0].ontouchstart = (e) => {this.startDraw(e)};
res[0].ontouchmove = (e) => {this.draw(e)};
res[0].ontouchend = () => {this.endDraw()};
});
},
methods: {
startDraw(event){
let touches = event.touches[0];
this.lastX = touches.x;
this.lastY = touches.y;
this.isDrawing = true;
},
draw(event){
if (!this.isDrawing){return;}
let currentTouch = event.touches[0];
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(currentTouch.x, currentTouch.y);
this.ctx.stroke();
this.lastX = currentTouch.x;
this.lastY = currentTouch.y;
},
endDraw(){
this.isDrawing = false;
},
clearSignature(){
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
},
saveSignatureAsImage(){
var tempFilePath = this.ctx.canvas.toDataURL("image/png");
console.log(tempFilePath); // 可在此处进一步处理图像数据
// 或者使用uni.uploadFile API上传至服务器
/*
uni.uploadFile({
url: 'https://example.com/upload',
filePath: tempFilePath,
name: 'file',
success: function(res){
console.log('upload successful!');
}
});
*/
}
}
}
</script>
<style scoped>
.signature-pad{
width: 100%;
height: auto;
}
#myCanvas{
border: 1px solid black;
background-color:white;
}
</style>
```
上述代码片段展示了怎样初始化 Canvas 并配置基本的绘图逻辑,包括开始绘画、移动手指时持续作画以及结束绘画的动作捕捉。此外还提供了两个辅助函数分别用来清空当前画板上的内容和将用户的签名转换成 Base64 编码形式以便后续操作或存储[^3]。
#### 注意事项
- 对于 Android 设备可能出现轻微延迟的情况,在实际项目中可能需要针对性能做额外优化。
- 如果希望提高用户体验,则可以在界面上增加更多交互元素比如撤销最近一笔等功能。
- 当涉及到敏感信息如个人身份认证时,请务必遵循当地法律法规关于隐私保护的规定。
阅读全文
相关推荐


















